How to manipulate hexadecimal value in Bash?

17,248

To print hex number as string you can

printf 0x%X $MYVAR

to increment it and print it back in hex you can do, for example

printf 0x%X `echo $(( 0xfe + 1 ))`

For "convert back" to the original format I think you mean keep the integer value, in this case you can simply use $MYVAR without format conversion.

Hope this helps,
Regards.

EDIT :
To follow your question editing, I'll add my answer below.

You could set MYVAR in this way:

read dummy MYVAR <<EOF
`dd if=tempfile skip=8001 count=1 bs=1|od -x`
EOF

Now you have hex value of the byte read from file stored in MYVALUE.
You can now print it directly with echo, printf or whatever.

$ echo $MYVAR
00fe

You can perform math on it as said before:

$ printf %X $((0x$MYVAR + 1))
FF

(thanks to fedorqui for the shortest version)

Regards.

Share:
17,248
michelemarcon
Author by

michelemarcon

Hello, I'm a Java software engineer. I also have some Android and Linux experience.

Updated on June 04, 2022

Comments

  • michelemarcon
    michelemarcon almost 2 years

    I have a variable with an hexadecimal value: in this example, a byte with value 0xfe:

    echo $MYVAR | hexdump
    
    0000000 0afe
    0000002
    

    I want to use this value on my bash script, in particular I need to:

    1. use as a string (echo X$MYVAR should give me Xfe)

    2. increment it, (0xff)

    3. convert back to the original format (I need to save the incremented value for future use)

    Maybe it would be easier if I convert it into integer format?

    EDIT: here is how I initialize the var:

    printf "\xfe" | dd bs=1 of=tempfile seek=8001
    MYVAR=`dd if=tempfile skip=8001 count=1 bs=1`
    
  • wizard
    wizard almost 11 years
    @michelemarcon have you initialized MYVAR with a number prior to call printf? ex. MYVAR=0
  • fedorqui
    fedorqui almost 11 years
    For point 2) "Increment" you can use printf "%X" $((MYVAR + 1))
  • michelemarcon
    michelemarcon almost 11 years
    Awesome! Only the last point remains: how to convert the "FF" string back to 1 byte value (rewrite the value on the file)?
  • wizard
    wizard almost 11 years
    @michelemarcon use it with the 0x prefix, and BASH will handle it as a number in every situation.
  • wizard
    wizard almost 11 years
    @michelemarcon It's normal, $MYVAR alredy is in hex format, if you prepend 0x bash take the number represented by that hex string, and then you print it again in %X (hex) format, so you get again FE. What did you want to obtain with that syntax?
  • michelemarcon
    michelemarcon almost 11 years
    Fount it! MYVAR=`echo $MYVAR | cut -c3-4`; printf "\x$MYVAR"