Home > Software engineering >  bash : trying to write a 32bit integer as 4 byte on binary file, end up with 8 byte
bash : trying to write a 32bit integer as 4 byte on binary file, end up with 8 byte

Time:01-08

I try to write some headers on a binary file, the rest of operation (bin file merging etc) are on a batch file but apparently batch is no good to write directly on binary files, i could not manage to write anything else than hex representation, so i moved to bash (under cygwin), and after some struggle i can write bytes on the binary file from a 32 bit integer, however it writes 8 bytes instead of 4, each byte is followed by 0x0D.

So here is the bash script:

HEXSTR=`printf "x" $1`
BYTE1=`echo -n "$HEXSTR" | cut -c 1-2`
BYTE2=`echo -n "$HEXSTR" | cut -c 3-4`
BYTE3=`echo -n "$HEXSTR" | cut -c 5-6`
BYTE4=`echo -n "$HEXSTR" | cut -c 7-8`
echo $HEXSTR
echo $BYTE1 
echo $BYTE2
echo $BYTE3
echo $BYTE4
echo -ne "\x$BYTE4\x$BYTE3\x$BYTE2\x$BYTE1" | dd of="header.bin" bs=1 seek=388 conv=notrunc

It takes the ineger as argument, in this case 516877. And here is the output on the terminal

C:\size.sh 5168772
004ede84
 0
4e
de
84
8 0 records in
8 0 records out
8 bytes (8 B) copied, 0.0002827 s, 28.3 kB/s

and here is the hex view of what has been written on the file:

file view

So, i can see the 4 bytes 00 4E DE 84 have been written, however each is followed with 0D, what am i doing wrong? What i try to do is write 84DE4E00 (5168772) at the position 388.

Also i want to precise that i have seen some solution involving xxd however for some reason this is not recognized on my system (win10 with cygwin) so sadly i cannot use that.

CodePudding user response:

You can try this script:

#!/bin/bash

num=$1
printf -v esc '\\x%x' \
    $((num%6)) $((num/2**8%6)) $((num/2**16%6)) $((num/2**24))
printf '%b' "$esc" | dd of="header.bin" bs=1 seek=388 conv=notrunc
  • Related