1

I am iterating over hex digits in a string using a for loop. I can extract each hex digit ok, but my code to convert to a number is giving strange values. How can I fix this code?

Script:

#!/bin/bash

mystring="5e51584a4c"

for (( i = 0; i < ${#mystring}; i = i + 2)); do
    snumber="${mystring:i:2}"
    printf "number as string=%s\n" $snumber
    number=$(printf "%x"  "'${mystring:i:2}")
    printf "number=%d\n" $number
done

I am getting this output:

number as string=5e
number=35
number as string=51
number=35
number as string=58
number=35
number as string=4a
number=34
number as string=4c
number=34

3 Answers 3

5

You don't need printf in this case, you can use bash's $((base#number)) construct.

#!/bin/bash -

mystring="5e51584a4c"

for ((i=0; i<${#mystring}; i+=2)); do
    snumber="${mystring:i:2}"
    echo "number as string=${snumber}"
    echo "number=$((16#${snumber}))"
done
Sign up to request clarification or add additional context in comments.

Comments

4

Hex numbers need to have 0x prefix:

printf "%d\n" 0x5e

Outputs:

94

mystring="5e51584a4c"

for (( i = 0; i < ${#mystring}; i = i + 2)); do
    snumber="${mystring:i:2}"
    printf "number=%d\n" 0x$snumber
done

Comments

3

Your printf command is printing the character code of the first digit in each substring, because you have the ' prefix to the argument. You want a 0x prefix instead.

When printing as hexadecimal, you can use %#x conversion to make printf emit the leading 0x prefix needed by the next usage:

number=$(printf '%#x'  "0x${mystring:i:2}")
#                ^^^    ^^

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.