击:写整数二进制文件 [英] Bash: write integer to binary file

查看:189
本文介绍了击:写整数二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/2746707/using-bash-write-bit-re$p$psentation-of-integer-to-file\">using庆典:写位重新整数文件的presentation

Possible Duplicate:
using bash: write bit representation of integer to file

我需要一个文件的大小写入一个二进制文件。例如:

I need to write the size of a file into a binary file. For example:

$ stat -c %s in.txt 
68187

$ stat -c %s in.txt >> out.bin

而不是写68187字符串out.bin的,我想写的168187在4个字节INT再presentation到out.bin。

Instead of writing "68187" string to out.bin, i want to write the 4 bytes int representation of 168187 to out.bin.

我如何转换68187至4个字节INT?

How can i convert "68187" to 4 bytes int?

推荐答案

这是我能想出的:

int=65534
printf "0: %.8x" $int | xxd -r -g0 >>file

现在根据字节序你可能希望交换的字节顺序:

Now depending on endianness you might want to swap the byte order:

printf "0: %.8x" $int | sed -E 's/0: (..)(..)(..)(..)/0: \4\3\2\1/' | xxd -r -g0 >>file

示例(德codeD,所以它是可见的):

Example (decoded, so it's visible):

printf "0: %.8x" 65534 | sed -E 's/0: (..)(..)(..)(..)/0: \4\3\2\1/' | xxd -r -g0 | xxd
0000000: feff 0000                                ....

这是对的符号的INT,如果int是的签名和的值的的你要计算补。简单的数学。

This is for unsigned int, if the int is signed and the value is negative you have to compute the two's complement. Simple math.

这篇关于击:写整数二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆