Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

shell - How to perform bitwise operations on hexadecimal numbers in bash?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, XOR and/or NOT:

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

And to get the result in hex as well:

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

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

$ printf '%X
' "$(( 0x12345678 ^ 0xDEADBEEF ))"     # Bitwise XOR
CC99E897

$ printf '%X
' "$(( ~ 0x2C8B ))"                    # Bitwise NOT
FFFFFFFFFFFFD374

The only detail with a bitwise not (~) is that it flips all available bits. If the number representation use 64 bits, the result will have 64 bits. All leading zero bits will be flipped to ones.

To limit such conversion just use an AND:

$ printf '%X
' "$(( ( ~ 0x2C8B ) & 0xFFFF ))"
D374

Note that a bitwise not ~ is not a logic not !. A logic not turns into 0 or 1 only, not any other number.

$ printf '%X
' "$(( ! 0xdead ))" "$(( ! 0 ))"
0
1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...