Search code examples
linuxxxd

Converting integers to binary with xxd


I have a file, output.log, that has a list of space, ' ', separated integers ranging from [-2048,2048]. I am attempting to convert this to a binary file with xxd. I'm using the command,

xxd -r -p output.log > output.bin

However when I read the file back with xxd I lose all of the signs (-) and receive some values greater than 2048. Is there a better way to do this? Thanks.

edit: With sample data...

$ cat test
4 0 -3 -2 -1 200

$ xxd -r -p test > test.bin

$ xxd test.bin
0000000: 4012 00            @..

Maybe I am misunderstanding what xxd is doing, what I expected to see after the last command is to see my original input data being displayed back. Is this not correct?

With much larger data sets I will see the correct values show up from time to time but there is still a ton of noise in the output.


Solution

  • There may be some strange characters in your input source file, xxd works just fine with numbers. Try looking at your data using octal dump od -c input to look for anything strange.

    $ echo '-3000 -2048 -1 0 1 2048 3000' > foo.input
    $ cat foo.input
    -3000 -2048 -1 0 1 2048 3000
    $ xxd foo.input > foo.hex
    $ cat foo.hex
    0000000: 2d33 3030 3020 2d32 3034 3820 2d31 2030  -3000 -2048 -1 0
    0000010: 2031 2032 3034 3820 3330 3030 0a          1 2048 3000.
    $ xxd -r foo.hex > foo.output
    $ cat foo.output
    -3000 -2048 -1 0 1 2048 3000