Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent hexadecimal number with two digits in linux scripts (bash)

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

like image 770
amigal Avatar asked Sep 20 '12 11:09

amigal


2 Answers

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
like image 53
unwind Avatar answered Sep 30 '22 05:09

unwind


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.

like image 45
user4815162342 Avatar answered Sep 30 '22 06:09

user4815162342