How to perform bitwise operations on hexadecimal n

2019-02-12 04:27发布

In my bash script I have a string containing a hexadecimal number, e.g. hex="0x12345678". Is it possible to treat it as a hex number and do bit shifting on it?

标签: bash shell sh
3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-02-12 04:54

You can easily bitshift such numbers in an arithmetic context:

$ hex="0x12345678"
$ result=$((hex << 1))
$ printf "Result in hex notation: 0x%x\n" "$result"
0x2468acf0
查看更多
手持菜刀,她持情操
3楼-- · 2019-02-12 04:57

Yes.

Arithmetic expressions support base 16 numbers and all the usual C operators.

Example:

$ hex="0xff"
$ echo $(( hex >> 1 ))
127
查看更多
霸刀☆藐视天下
4楼-- · 2019-02-12 05:03

Of course you can do bitwise operations (inside an Arithmetic Expansion):

$ echo "$((0x12345678 << 1))"
610839792

Or:

$ echo "$(( 16#12345678 << 1 ))"
610839792

The value could be set in a variable as well:

$ var=0x12345678         # or var=16#12345678
$ echo "$(( var << 1 ))"
610839792

And you can do OR, AND and XOR:

$ echo "$(( 0x123456 | 0x876543 ))"
9925975

And to get the result in hex as well:

$ printf '%X\n' "$(( 0x12345678 | 0xDEADBEEF ))"     # Bitwise OR
DEBDFEFF

$ printf '%X\n' "$(( 0x12345678 & 0xDEADBEEF ))"     # Bitwise AND
12241668

$ printf '%X\n' "$(( 0x12345678 ^ 0xDEADBEEF ))"     # Bitwise XOR
CC99E897
查看更多
登录 后发表回答