6

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

2
  • Internal representation don't care about leading zeros(or decimal or hexadecimal, it's just a number), skip that, and add it when displaying the data instead; using printf and the %X-modifier Commented Sep 20, 2012 at 11:36
  • I am using an ipmi interface. I am controlling blades in slots through the chassis shelf manager. this protocol requires everything to be represented in two digits Commented Sep 20, 2012 at 11:44

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

@user4815162342 Thanks! I should have tested it prior to posting, apologies. I couldn't delete the answer due to it being accepted, so I edited instead. I believe it works now (I did test).
6

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.