convert binary data to hex in shell script?

2020-02-17 04:53发布

feel a bit stupid asking this (sounds as basics) but can't find an answer elsewhere. I want to convert binary data to hex, just that, no fancy formatting and all. hexdump seems too clever, it "overformats" for me. I want to take x bytes from the /dev/random and pass them on as hex.

Preferably I'd like to use only standard linux tools, so that I don't need to install it on every machine (there are many)

8条回答
孤傲高冷的网名
2楼-- · 2020-02-17 05:32

Perhaps you could write your own small tool in C, and compile it on-the-fly:

int main (void) {
  unsigned char data[1024];
  size_t numread, i;

  while ((numread = read(0, data, 1024)) > 0) {
    for (i = 0; i < numread; i++) {
      printf("%02x ", data[i]);
    }
  }

  return 0;
}

And then feed it from the standard input:

cat /bin/ls | ./a.out

You can even embed this small C program in a shell script using the heredoc syntax.

查看更多
啃猪蹄的小仙女
3楼-- · 2020-02-17 05:33

This 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
查看更多
登录 后发表回答