Home > Archive > AWK > May 2005 > Function to convert integer to binary
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Function to convert integer to binary
|
|
| Bill Seivert 2005-05-26, 3:55 am |
| Hi,
I know I could write one, but if someone has one, it would save me
some time.
function binary(inp, size)
inp and size are positive whole (integer) values, possibly zero.
If size is zero, no leading zeroes, (though if inp = 0, output is 0).
If size is non-zero, leading zeroes.
If size is too small for input, assume zero.
Samples:
inp size return value
5 4 0101
15 8 00001111
60 0 111100
60 8 00111100
60 4 111100
You get the idea.
So, in a script it would look like:
binstring = binary(inp, size);
printf ("%s\n", binstring);
nawk on Sun Solaris.
Thanks in advance.
Bill Seivert
| |
| Ted Davis 2005-05-26, 3:56 pm |
| On Wed, 25 May 2005 22:13:52 -0600, Bill Seivert <seivert@pcisys.not>
wrote:
>Hi,
>
>I know I could write one, but if someone has one, it would save me
>some time.
>
>function binary(inp, size)
>
>inp and size are positive whole (integer) values, possibly zero.
>If size is zero, no leading zeroes, (though if inp = 0, output is 0).
>If size is non-zero, leading zeroes.
>If size is too small for input, assume zero.
>
>Samples:
>inp size return value
> 5 4 0101
> 15 8 00001111
> 60 0 111100
> 60 8 00111100
> 60 4 111100
>
>You get the idea.
>
>So, in a script it would look like:
> binstring = binary(inp, size);
> printf ("%s\n", binstring);
>
>
>nawk on Sun Solaris.
This may be gawk specific:
function binstring(Number, Quads ){
if( !Quads ) Quads = 4
B[ "0" ] = "0000"
B[ "1" ] = "0001"
B[ "2" ] = "0010"
B[ "3" ] = "0011"
B[ "4" ] = "0100"
B[ "5" ] = "0101"
B[ "6" ] = "0110"
B[ "7" ] = "0111"
B[ "8" ] = "1000"
B[ "9" ] = "1001"
B[ "A" ] = "1010"
B[ "B" ] = "1011"
B[ "C" ] = "1100"
B[ "D" ] = "1101"
B[ "E" ] = "1110"
B[ "F" ] = "1111"
n = sprintf("%0" Quads "X", Number)
x = split( n, A, "")
s = ""
for( y = 1; y <= x; y++ ) {
s = s B[ A[ y ] ]
}
return s
}
There are also some differences between the speck and the function,
notably the return is organized in four bit quads - each quad has
leading zeros and the size is limited to multiples of four bits since
it is passed as the number of quads.
Tha approach is to convert the given number to hex, then use the
individual characters in the hex number string as indexes into a
lookup table.
--
T.E.D. (tdavis@gearbox.maem.umr.edu)
SPAM filter: Messages to this address *must* contain "T.E.D."
somewhere in the body or they will be automatically rejected.
| |
| Kenny McCormack 2005-05-26, 3:56 pm |
| In article <4pkb91lr4rd60n3ib606bdoqnmuvnuoc0n@4ax.com>,
Ted Davis <tdavis@gearbox.maem.umr.edu> wrote:
....
>This may be gawk specific:
I don't see anything per se gawk-specific - I'm guessing that your concern
is the %X option in sprintf - and the general problem that vendor AWKs tend
to be generally broken, in not always known/specific ways.
If you wanted to really be gawk-specific, you'd be using the bit functions
(and(), not(), or(), etc). That was my initial idea for a way to do it.
> function binstring(Number, Quads ){
> if( !Quads ) Quads = 4
> B[ "0" ] = "0000"
> B[ "1" ] = "0001"
> B[ "2" ] = "0010"
> B[ "3" ] = "0011"
> B[ "4" ] = "0100"
> B[ "5" ] = "0101"
> B[ "6" ] = "0110"
> B[ "7" ] = "0111"
> B[ "8" ] = "1000"
> B[ "9" ] = "1001"
> B[ "A" ] = "1010"
> B[ "B" ] = "1011"
> B[ "C" ] = "1100"
> B[ "D" ] = "1101"
> B[ "E" ] = "1110"
> B[ "F" ] = "1111"
> n = sprintf("%0" Quads "X", Number)
> x = split( n, A, "")
> s = ""
> for( y = 1; y <= x; y++ ) {
> s = s B[ A[ y ] ]
> }
> return s
> }
>
>There are also some differences between the speck and the function,
>notably the return is organized in four bit quads - each quad has
>leading zeros and the size is limited to multiples of four bits since
>it is passed as the number of quads.
>
>Tha approach is to convert the given number to hex, then use the
>individual characters in the hex number string as indexes into a
>lookup table.
This idea is pretty good - it was my original thought as well when
I thought of the idea of trying to use printf, realizing that printf
doesn't have a binary specifier, but that it does have hex, and hex is
pretty easy to convert to binary.
But then I realized that simplest is best, and the method below is
something I learned a million years ago - and it works for any base
conversion (try replacing the 2s with other numbers).
{s="";for (t=$0; t; t = int(t/2)) s = (t % 2) s;print s}
| |
| William Park 2005-05-26, 3:56 pm |
| Bill Seivert <seivert@pcisys.not> wrote:
> Hi,
>
> I know I could write one, but if someone has one, it would save me
> some time.
>
> function binary(inp, size)
>
> inp and size are positive whole (integer) values, possibly zero.
> If size is zero, no leading zeroes, (though if inp = 0, output is 0).
> If size is non-zero, leading zeroes.
> If size is too small for input, assume zero.
>
> Samples:
> inp size return value
> 5 4 0101
> 15 8 00001111
> 60 0 111100
> 60 8 00111100
> 60 4 111100
>
> You get the idea.
>
> So, in a script it would look like:
> binstring = binary(inp, size);
> printf ("%s\n", binstring);
>
>
> nawk on Sun Solaris.
>
> Thanks in advance.
> Bill Seivert
You got Awk answers. If you're looking for Bash solution, then this is
a feature I added to Bash shell, this w as matter of fact. :-)
binary [-boh] number...
Convert decimal to binary (default -b), octal (-o), or hex (-h)
number. Use $((base#number)) to convert back to decimal.
Eg.
binary 60 --> 111100
I'll add padding today. Until then, you have to do it manually, like
a=`binary 60`
a=${a|%8}
a=${a// /0}
or in one-shot,
printf '%8s\n' `binary 60` | sed 's/ /0/g'
It's not released to the public, yet. See
http://home.eol.ca/~parkw/bashdiff/...f-1.17rc.tar.gz
http://home.eol.ca/~parkw/index.html#bash
http://freshmeat.net/projects/bashdiff/
--
William Park <opengeometry@yahoo.ca>, Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
http://home.eol.ca/~parkw/thinflash.html
| |
| Ted Davis 2005-05-26, 8:55 pm |
| On Thu, 26 May 2005 15:14:44 GMT, gazelle@yin.interaccess.com (Kenny
McCormack) wrote:
>{s="";for (t=$0; t; t = int(t/2)) s = (t % 2) s;print s}
That's a partial solution - it still needs leading zeros. printf() or
sprintf() should take care of that.
I have no idea why I prefer LUT solutions to calculations, up to about
16 or so entries. Maybe it has to do with how easy they are in awk.
--
T.E.D. (tdavis@gearbox.maem.umr.edu)
SPAM filter: Messages to this address *must* contain "T.E.D."
somewhere in the body or they will be automatically rejected.
| |
| William Park 2005-05-27, 3:56 am |
| William Park <opengeometry@yahoo.ca> wrote:
> Bill Seivert <seivert@pcisys.not> wrote:
....[color=darkred]
> I'll add padding today. Until then, you have to do it manually, like
Done. Usage is
binary [-oOhH] [-w width] number...
Convert decimal to binary (default), octal (-o), or hex (-h)
number. You can use $((base#number)) to convert back to
decimal. If '-w' is specified, the number is zero-padded up to
'width'. Options -[OH] add 0 or 0x prefix to the number.
So, the above examples will go something like
binary -w4 5
binary -w8 15
binary -w0 60
binary -w8 60
binary -w4 60
> It's not released to the public, yet. See
> http://home.eol.ca/~parkw/bashdiff/...f-1.17rc.tar.gz
> http://home.eol.ca/~parkw/index.html#bash
> http://freshmeat.net/projects/bashdiff/
New 1.17rc has been uploaded.
Any other idea?
--
William Park <opengeometry@yahoo.ca>, Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
http://home.eol.ca/~parkw/thinflash.html
| |
| Bill Seivert 2005-05-28, 3:56 am |
|
Bill Seivert wrote:
> Hi,
>
> I know I could write one, but if someone has one, it would save me
> some time.
>
> function binary(inp, size)
>
> inp and size are positive whole (integer) values, possibly zero.
> If size is zero, no leading zeroes, (though if inp = 0, output is 0).
> If size is non-zero, leading zeroes.
> If size is too small for input, assume zero.
>
> Samples:
> inp size return value
> 5 4 0101
> 15 8 00001111
> 60 0 111100
> 60 8 00111100
> 60 4 111100
>
> You get the idea.
>
> So, in a script it would look like:
> binstring = binary(inp, size);
> printf ("%s\n", binstring);
>
>
> nawk on Sun Solaris.
>
> Thanks in advance.
> Bill Seivert
>
The solution I developed is a variant of Ted's proposal.
For use in another awk script, just cut-and-paste the function.
As is, it is a standalone test program.
Thanks to all.
Full listing follows:
function binary(inp, size , binout, bolen, i, octl, olen) {
# Avoid initializing multiple times.
# bintrip is global.
if (!("7" in bintrip)) {
bintrip["0"] = "000";
bintrip["1"] = "001";
bintrip["2"] = "010";
bintrip["3"] = "011";
bintrip["4"] = "100";
bintrip["5"] = "101";
bintrip["6"] = "110";
bintrip["7"] = "111";
}
octl = sprintf ("%0o", inp);
binout = "";
olen = length (octl);
for (i = olen; i > 0; --i) {
ochr = substr (octl, i, 1);
# Could use binout = sprintf ("%s%s", bintrip[ochr], binout);
binout = bintrip[ochr] binout;
}
if (size == 0) {
# Remove leading zeros.
sub (/^0*1/, "1", binout);
# If the answer is all zeros, make it one zero.
sub (/^00*$/, "0", binout);
}
else {
# Get the length of the binary string.
bolen = length (binout);
# Make a copy of it.
nz = binout;
# Remove leading zeros.
sub (/^0*1/, "1", nz);
# Handle the zoo zeros case.
sub (/^00*$/, "0", nz);
if (length (nz) > size) {
# Needs more than size characters, use the nz value.
binout = nz;
}
else if (bolen > size) {
# Get the right-most size characters.
binout = substr (binout, bolen - size + 1);
}
else {
# Need more leading zeros.
for (i = bolen; i < size; ++i) {
# Could use binout = sprintf ("0%s", binout);
binout = "0" binout;
}
}
}
# Return the string.
return binout;
}
{ # Main
if ($1 == "q") {
# Quit the test program.
exit;
}
out = binary(0 + $1, 0 + $2);
printf ("inp %3d, size %2d, out \"%s\".\n",
0 + $1, 0 + $2, out);
}
| |
| Ted Davis 2005-05-30, 8:55 am |
| On Thu, 26 May 2005 15:14:44 GMT, gazelle@yin.interaccess.com (Kenny
McCormack) wrote:
>{s="";for (t=$0; t; t = int(t/2)) s = (t % 2) s;print s}
That's a partial solution - it still needs leading zeros. printf() or
sprintf() should take care of that.
I have no idea why I prefer LUT solutions to calculations, up to about
16 or so entries. Maybe it has to do with how easy they are in awk.
--
T.E.D. (tdavis@gearbox.maem.umr.edu)
SPAM filter: Messages to this address *must* contain "T.E.D."
somewhere in the body or they will be automatically rejected.
|
|
|
|
|