I have a problem. I must represent each number with exactly 2 digits (i.e. 0F instead of F)
my code looks something like that:
1. read number of ascii chars are in an environment variable (using wc -w)
2. converting this number to hexadecimal (using bc).
How can I make sure the number I'll get after stage 2 will include a leading 0 (if necessary)
Thanks, Amigal
Run it through printf
:
$ printf "%02s" 0xf
0f
If you have the digits of the number only in a variable, say $NUMBER
, you can concatenate it with the required 0x
prefix directly:
$ NUMBER=fea
$ printf "%04x" 0x$NUMBER
0fea
Skip the conversion part in bc
and convert the decimal number with the printf
command:
#num=$(... | wc -w)
num=12 # for testing
printf "%02x" $num
0c
If you must convert to hexadecimal for other reasons, then use the 0x
prefix to tell printf
that the number is already hexadecimal:
#num=$(... | wc -w | bc ...)
num=c # as obtained from bc
printf "%02x" 0x$num
0c
The %x
format requests formatting the number as hexadecimal, %2x
requests padding to width of two characters, and %02x
specifically requests padding with leading zeros, which is what you want. Refer to the printf
manual (man printf
or info coreutils printf
) for more details on possible format strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With