如何在 bash 中对十六进制数执行按位运算?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40667382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to perform bitwise operations on hexadecimal numbers in bash?
提问by Jimmy Xu
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
脚本中,我有一个包含十六进制数的字符串,例如hex="0x12345678"
. 是否可以将其视为十六进制数并对其进行位移?
采纳答案by that other guy
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
回答by Isaac
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:
你可以做 OR、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