Convert binary data to hexadecimal in a shell script

后端 未结 8 1503
日久生厌
日久生厌 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:15

    All the solutions seem to be hard to remember or too complex. I find using printf the shortest one:

    $ printf '%x\n' 256
    100
    

    But as noted in comments, this is not what author wants, so to be fair, below is the full answer.

    ... to use above to output actual binary data stream:

    printf '%x\n' $(cat /dev/urandom | head -c 5 | od -An -vtu1)
    

    What it does:

    • printf '%x\n' .... - prints a sequence of integers , i.e. printf '%x,' 1 2 3, will print 1,2,3,
    • $(...) - this is a way to get output of some shell command and process it
    • cat /dev/urandom - it outputs random binary data
    • head -c 5 - limits binary data to 5 bytes
    • od -An -vtu1 - octal dump command, converts binary to decimal

    As a testcase ('a' is 61 hex, 'p' is 70 hex, ...):

    $ printf '%x\n' $(echo "apple" | head -c 5 | od -An -vtu1)
    61
    70
    70
    6c
    65
    

    Or to test individual binary bytes, on input let’s give 61 decimal ('=' char) to produce binary data ('\\x%x' format does it). The above command will correctly output 3d (decimal 61):

    $printf '%x\n' $(echo -ne "$(printf '\\x%x' 61)" | head -c 5 | od -An -vtu1)
    3d
    

提交回复
热议问题