I'm running on a scaled down version of CentOS 5.5 without many tools available. No xxd, bc, or hd. I can't install any additional utilities, unfortunately. I do have od, dd, awk, and bourne shell (not bash). What I'm trying to do is relatively simple in a normal environment. Basically, I have a number, say 100,000, and I need to store its binary representation in a file. Typically, I'd do something like ...
printf '%x' "100000" | xxd -r -p > file.bin
If you view a hex dump of the file, you'd correctly see the number represented as 186A0.
Is there an equivalent I can cobble together using the limited tools I have available? Pretty much everything I've tried stores the ascii values for the digits.
You can do it with a combination of your printf, awk, and your shell.
#!/usr/bin/env awk
# ascii_to_bin.awk
{
# Pad out the incoming integer to a full byte
len = length($0);
if ( (len % 2) != 0) {
str = sprintf("0%s", $0);
len = len + 1;
}
else {
str = $0;
}
# Create your escaped echo string
printf("echo -n -e \"");
for(i=1;i<=len;i=i+2) {
printf("\\\\x%s", substr(str, i, 2));
}
printf("\"");
}
Then you can just do
$ printf '%x' "100000" | awk -f ascii_to_bin.awk | /bin/sh > output.bin
If you know your target binary length you can just do a printf "%0nX"
(n
is the target size) and remove the (len % 2)
logic.