pio*_*kkr 8 text-processing conversion binary replace
我试图在二进制文件中找到两个字节,然后增加这两个字节的值并在文件中替换它们。这两个字节位于位置 0x82-0x83。现在我已经使用这个成功提取了这两个字节:
#!/usr/bin/env bash
BYTES=$(tail -c +131 "$1" | head -c 2)
Run Code Online (Sandbox Code Playgroud)
这些字节具有值:1B 1F
. 我坚持:
6943
十进制。head -c 130 original.bin >> new_file.bin && magic_command_writing_bytes_to_file >> new_file.bin && tail -c +133 original.bin
,但必须有更好的方法。我可以在 PHP 中做到这一点,它应该更容易,但我对如何在 bash 中做到这一点很感兴趣。
用这个文件测试:
$ echo hello world > test.txt
$ echo -n $'\x1b\x1f' >> test.txt
$ echo whatever >> test.txt
$ hexdump -C test.txt
00000000 68 65 6c 6c 6f 20 77 6f 72 6c 64 0a 1b 1f 77 68 |hello world...wh|
00000010 61 74 65 76 65 72 0a |atever.|
$ grep -a -b --only-matching $'\x1b\x1f' test.txt
12:
Run Code Online (Sandbox Code Playgroud)
所以在这种情况下1B 1F
是在位置12
。
转换为整数(可能有更简单的方法)
$ echo 'ibase=16; '`xxd -u -ps -l 2 -s 12 test.txt` | bc
6943
Run Code Online (Sandbox Code Playgroud)反过来:
$ printf '%04X' 6943 | xxd -r -ps | hexdump -C
00000000 1b 1f |..|
$ printf '%04X' 4242 | xxd -r -ps | hexdump -C
00000000 10 92 |..|
Run Code Online (Sandbox Code Playgroud)并将其放回文件中:
$ printf '%04X' 4242 | xxd -r -ps | dd of=test.txt bs=1 count=2 seek=12 conv=notrunc
2+0 records in
2+0 records out
2 bytes (2 B) copied, 5.0241e-05 s, 39.8 kB/s
Run Code Online (Sandbox Code Playgroud)结果:
$ hexdump -C test.txt
00000000 68 65 6c 6c 6f 20 77 6f 72 6c 64 0a 10 92 77 68 |hello world...wh|
00000010 61 74 65 76 65 72 0a |atever.|
Run Code Online (Sandbox Code Playgroud)