如何在 Bash 中操作十六进制值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16914418/
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-18 05:36:11  来源:igfitidea点击:

How to manipulate hexadecimal value in Bash?

bashshellhex

提问by michelemarcon

I have a variable with an hexadecimal value: in this example, a byte with value 0xfe:

我有一个带有十六进制值的变量:在这个例子中,一个值为 0xfe 的字节:

echo $MYVAR | hexdump

0000000 0afe
0000002

I want to use this value on my bash script, in particular I need to:

我想在我的 bash 脚本中使用这个值,特别是我需要:

  1. use as a string (echo X$MYVAR should give me Xfe)

  2. increment it, (0xff)

  3. convert back to the original format (I need to save the incremented value for future use)

  1. 用作字符串(echo X$MYVAR 应该给我 Xfe)

  2. 增加它,(0xff)

  3. 转换回原始格式(我需要保存增量值以备将来使用)

Maybe it would be easier if I convert it into integer format?

如果我将其转换为整数格式,也许会更容易?

EDIT: here is how I initialize the var:

编辑:这是我初始化 var 的方式:

printf "\xfe" | dd bs=1 of=tempfile seek=8001
MYVAR=`dd if=tempfile skip=8001 count=1 bs=1`

回答by wizard

To print hex number as string you can

要将十六进制数字打印为字符串,您可以

printf 0x%X $MYVAR

to increment it and print it back in hex you can do, for example

例如,要增加它并以十六进制打印回来,您可以这样做

printf 0x%X `echo $(( 0xfe + 1 ))`

For "convert back" to the original format I think you mean keep the integer value, in this case you can simply use $MYVARwithout format conversion.

对于“转换回”原始格式,我认为您的意思是保留整数值,在这种情况下,您可以简单地使用$MYVAR而不进行格式转换。

Hope this helps,
Regards.

希望这有帮助,
问候。

EDIT :
To follow your question editing, I'll add my answer below.

编辑:
要按照您的问题进行编辑,我将在下面添加我的答案。

You could set MYVAR in this way:

你可以这样设置 MYVAR:

read dummy MYVAR <<EOF
`dd if=tempfile skip=8001 count=1 bs=1|od -x`
EOF

Now you have hex value of the byte read from file stored in MYVALUE.
You can now print it directly with echo, printfor whatever.

现在您拥有从存储在 MYVALUE 中的文件中读取的字节的十六进制值。
现在,您可以直接与打印echoprintf或什么的。

$ echo $MYVAR
00fe

You can perform math on it as said before:

您可以像之前所说的那样对其进行数学运算:

$ printf %X $((0x$MYVAR + 1))
FF

(thanks to fedorqui for the shortest version)

感谢 fedorqui 提供了最短的版本

Regards.

问候。