我需要在 bash 中执行操作。我有这个
401f
我喜欢在 bash 中执行这些操作:
这样:https : //gchq.github.io/CyberChef/#recipe=Swap_endianness('Hex',4,true)From_Base(16)&input=NDAxZg
所以结果应该是8000
。我喜欢使用尽可能少的依赖来做到这一点。我的意思是,如果可以仅使用 linux 核心实用程序来完成,那就太好了……我想会需要一些东西。不知道是什么,也许是 xxd、awk 也可以,但我想避免使用 bc 之类的东西。谢谢。
使用支持按位运算的算术扩展在 shell 中很容易做到。
num=401f
# Add a 0x prefix so it's treated as base 16 in shell arithmetic.
num="0x$num"
# Swap the bytes in a 16-bit number and print the result in base 10
printf "%d\n" $(( ((num & 0xFF) << 8) | (num >> 8) ))
# Or assign to a variable, etc.
newnum=$(( ((num & 0xFF) << 8) | (num >> 8) ))
bash
用于 16 位和 32 位字节交换的便捷函数:
bswap16() {
# Default to 0 if no argument given
local num="0x${1:-0}"
printf "%d\n" $(( ((num & 0xFF) << 8) | (num >> 8) ))
}
bswap32() {
local num="0x${1:-0}"
printf "%d\n" $(( ((num & 0xFF) << 24) |
(((num >> 8) & 0xFF) << 16) |
(((num >> 16) & 0xFF) << 8) |
(num >> 24) ))
}
bswap16 401f # 8000
bswap32 401f # 524288000
使用bash
的参数子字符串扩展的替代方法(与上述不同,此版本要求数字具有 4 个十六进制数字才能正常工作):
num=401f
echo $(("0x${num:2:2}${num:0:2}"))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句