Ascii/Hex convert in bash

前端 未结 15 1462
广开言路
广开言路 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:06

    The reason is because hexdump by default prints out 16-bit integers, not bytes. If your system has them, hd (or hexdump -C) or xxd will provide less surprising outputs - if not, od -t x1 is a POSIX-standard way to get byte-by-byte hex output. You can use od -t x1c to show both the byte hex values and the corresponding letters.

    If you have xxd (which ships with vim), you can use xxd -r to convert back from hex (from the same format xxd produces). If you just have plain hex (just the '4161', which is produced by xxd -p) you can use xxd -r -p to convert back.

    0 讨论(0)
  • 2020-12-12 21:07
    $> printf "%x%x\n" "'A" "'a"
    4161
    
    0 讨论(0)
  • 2020-12-12 21:08

    I use:

    > echo Aa | tr -d '\n' | xxd -p
    4161
    
    > echo 414161 | tr -d '\n' | xxd -r -p
    AAa
    

    The tr -d '\n' will trim any possible newlines in your input

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

    For the first part, try

    echo Aa | od -t x1
    

    It prints byte-by-byte

    $ echo Aa | od -t x1
    0000000 41 61 0a
    0000003
    

    The 0a is the implicit newline that echo produces.

    Use echo -n or printf instead.

    $ printf Aa | od -t x1
    0000000 41 61
    0000002
    
    0 讨论(0)
  • 2020-12-12 21:13

    I don't know how it crazy it looks but it does the job really well

    ascii2hex(){ a="$@";s=0000000;printf "$a" | hexdump | grep "^$s"| sed s/' '//g| sed s/^$s//;}
    

    Created this when I was trying to see my name in HEX ;) use how can you use it :)

    0 讨论(0)
  • 2020-12-12 21:13
    echo -n Aa | hexdump -e '/1 "%02x"'; echo
    
    0 讨论(0)
提交回复
热议问题