Ascii/Hex convert in bash

前端 未结 15 1463
广开言路
广开言路 2020-12-12 21:03

I\'m now doing it this way:

[root@~]# echo Aa|hexdump -v
0000000 6141 000a                              
0000003
[root@~]# echo -e \"\\x41\\x41\\x41\\x41\"
A         


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

    echo append a carriage return at the end.

    Use

    echo -e
    

    to remove the extra 0x0A

    Also, hexdump does not work byte-per-byte as default. This is why it shows you bytes in a weird endianess and why it shows you an extra 0x00.

    0 讨论(0)
  • 2020-12-12 21:15

    With bash :

    a=abcdefghij    
    for ((i=0;i<${#a};i++));do printf %02X \'${a:$i:1};done
    

    6162636465666768696A

    0 讨论(0)
  • 2020-12-12 21:15

    SteinAir's answer above was helpful to me -- thank you! And below is a way it inspired, to convert hex strings to ascii:

    for h in $(echo "4161" | sed "s/\(..\)/\1 /g"); do printf `echo "\x$h"`;done
    Aa
    
    0 讨论(0)
  • 2020-12-12 21:16

    here a little script I wrote to convert ascii to hex. hope it helps:

    echo '0x'"`echo 'ASCII INPUT GOES HERE' | hexdump -vC |  awk 'BEGIN {IFS="\t"} {$1=""; print }' | awk '{sub(/\|.*/,"")}1'  | tr -d '\n' | tr -d ' '`" | rev | cut -c 3- | rev
    
    0 讨论(0)
  • 2020-12-12 21:18

    For single line solution:

    echo "Hello World" | xxd -ps -c 200 | tr -d '\n'
    

    It will print:

    48656c6c6f20576f726c640a
    

    or for files:

    cat /path/to/file | xxd -ps -c 200 | tr -d '\n'
    

    For reverse operation:

    echo '48656c6c6f20576f726c640a' | xxd -ps -r
    

    It will print:

    Hello World
    
    0 讨论(0)
  • 2020-12-12 21:22
    jcomeau@aspire:~$ echo -n The quick brown fox jumps over the lazy dog | python -c "print raw_input().encode('hex'),"
    54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f67
    jcomeau@aspire:~$ echo -n The quick brown fox jumps over the lazy dog | python -c "print raw_input().encode('hex')," | python -c "print raw_input().decode('hex'),"
    The quick brown fox jumps over the lazy dog
    

    it could be done with Python3 as well, but differently, and I'm a lazy dog.

    0 讨论(0)
提交回复
热议问题