如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:27:39  来源:igfitidea点击:

How to perform bitwise operations on hexadecimal numbers in bash?

bashshellsh

提问by Jimmy Xu

In my bashscript 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

回答by Adrian Frühwirth

Yes.

是的

Arithmetic expressions support base 16 numbers and all the usual Coperators.

算术表达式支持基数为 16 的数字和所有常用C运算符。

Example:

例子:

$ hex="0xff"
$ echo $(( hex >> 1 ))
127