Convert binary data to hexadecimal in a shell script

后端 未结 8 1505
日久生厌
日久生厌 2020-12-13 05:59

I want to convert binary data to hexadecimal, just that, no fancy formatting and all. hexdump seems too clever, and it \"overformats\" for me. I want to take x

相关标签:
8条回答
  • 2020-12-13 06:21

    Watch out!

    hexdump and xxd give the results in a different endianness!

    $ echo -n $'\x12\x34' | xxd -p
    1234
    $ echo -n $'\x12\x34' | hexdump -e '"%x"'
    3412
    

    Simply explained. Big-endian vs. little-endian :D

    0 讨论(0)
  • 2020-12-13 06:30

    These three commands will print the same (0102030405060708090a0b0c):

    n=12
    echo "$a" | xxd -l "$n" -p
    echo "$a" | od  -N "$n" -An -tx1 | tr -d " \n" ; echo
    echo "$a" | hexdump -n "$n" -e '/1 "%02x"'; echo
    

    Given that n=12 and $a is the byte values from 1 to 26:

    a="$(printf '%b' "$(printf '\\0%o' {1..26})")"
    

    That could be used to get $n random byte values in each program:

    xxd -l "$n" -p                   /dev/urandom
    od  -vN "$n" -An -tx1            /dev/urandom | tr -d " \n" ; echo
    hexdump -vn "$n" -e '/1 "%02x"'  /dev/urandom ; echo
    
    0 讨论(0)
提交回复
热议问题