简体   繁体   English

是否可以使用 bash sript 将数字的二进制表示形式写入文件?

[英]Is it possible to write the binary representation of a number into a file using bash sript?

I need to write the 4 bytes representation of a number (176) into a .bin file.我需要将数字 (176) 的 4 字节表示写入 .bin 文件。 I was using the following command我正在使用以下命令

perl -we 'print pack "N", shift' 176 >> package.bin

and it works fine.它工作正常。 But now I'd need to do exactly the same thing without using perl.但是现在我需要在不使用 perl 的情况下做完全相同的事情。 Is it possible?是否可以? I can only find solutions with perl but unfortunatly I can't use it because of project requirements.我只能用 perl 找到解决方案,但不幸的是由于项目要求我不能使用它。

I also tried this solution:我也试过这个解决方案:

local n bit
for (( n=$1 ; n>0 ; n >>= 1 )); do  bit="$(( n&1 ))$bit"; done
echo -n -e $bit > tobin.bin

But it doesn't work because it writes 10110000 into my destination file and it is wrong because it is considered to be 8 bytes long and not 4 (1 byte for each character).但它不起作用,因为它将10110000写入我的目标文件,这是错误的,因为它被认为是 8 个字节长而不是 4 个字节(每个字符 1 个字节)。

Try尝试

num=176

printf -v oct0 '%03o' "$(( (num>>24) & 0xff ))"
printf -v oct1 '%03o' "$(( (num>>16) & 0xff ))"
printf -v oct2 '%03o' "$(( (num>> 8) & 0xff ))"
printf -v oct3 '%03o' "$(( num       & 0xff ))"

printf "\\$oct0\\$oct1\\$oct2\\$oct3" >package.bin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM