- 3 способа преобразовать hex в бинарный код на bash
- Converting from *.hex to *.bin for ARM on Linux
- 3 Answers 3
- convert a hex string to binary and send with netcat
- 4 Answers 4
- How to convert a text file to binary file using linux commands
- 3 Answers 3
- Convert binary data to hexadecimal in a shell script
- 8 Answers 8
3 способа преобразовать hex в бинарный код на bash
1. Используя sed
Зачем два printf в первом примере? Какой объем бинарных данных схавает переменная?
Не знаю, можно проверить
Ну для 2 символов — не спортивно.
Это как вы умудрились? Для кодировок utf-8 и koi8-r оно печатает ‘я’.
ГейОС или бздя какая-нибудь, небось.
На котором мой копирайт.
Слабо прочитать топик, перед тем как комментировать? Где тут ash в сообщениях увидели?
знаю, потому и вбросил, мол там не поддерживаются юникод-символы (или за это отвечает libc?). Надо будет кстати твой форк попробовать, но меня немного смущает разрыв в номере версий
Это mksh, локаль UTF-8.
Надо будет кстати твой форк попробовать
Ну это извращение там тоже не будет работать. Оно и понятно, ибо сделать, чтобы печатало ‘я’ в соотвествии с кодировкой — это море кода, который нафиг для busybox не впёрся.
Всё время забываю, что на ЛОРе топики не читают, за нитью комментов не следят. А чего не продемонстрируете shell без встроенного printf? Оно же совсем не обязательное. Я начинал с таких, оно тогда не только встроенное не было, а даже вообще такой утилиты не было.
3 способа преобразовать hex в бинарный код на bash
Источник
Converting from *.hex to *.bin for ARM on Linux
I want to upload program to my STM32F4 Discovery board using st-flash command. Problem is when I try to upload *.hex or *.elf file it is just not working. I tried many ways ( like using xxd ) of converting from *.elf or *.hex to *.bin but it is still not working when I upload it. And yes, I tried uploading hex file from other Windows computer and it works.
Sample ( first three lines, just to show you how it looks inside ) of hex file:
My OS is Ubuntu 14.04 LTS.
Thanks for help!
3 Answers 3
I assume you have linux and you have installed binutils , so you just do:
.hex file format is documented on the web. You need a loader program capable to understand it, as it has several kinds of registers to control the loading process. Some of the registers control entry point address. Others are data to be loaded at some fixed address.
You can get information at the wikipedia (I have found it there) for Intel Hex format (that’s how it is called). If all the data is on only one segment and no entry point is specified, theoretically you can convert it to binary data to be loaded, but that’s improbable.
It is a text file made of lines beginning with ‘:’ character, then comes a two field hex number representing the number of bytes of data this record has, then the address this data is to be loaded on, then the type of file, it can be one of:
- 00 This value is for a bunch of data, normally 16 bytes (0x10)
- 01 End of file. It has no data, so always is codified as :00000001FF
- 02 Extended segment address, to allow addresses with more than 16bit.
- 03 Start Entry point address, to register the initial CS:IP address in 0x86 architecture.
- 04 Extended Linear Address, to specify 32bit addresses. This specifies the upper 16bit address part of 00 registers.
- 05 Start Entry point Linear Address. This is the 32 bit linear entry point address.
Then comes n bytes (n is the value of the first field) of data (hex coded) to be loaded and finally a checksum byte (the sum in two’s complement of all the record bytes from the colon up).
Источник
convert a hex string to binary and send with netcat
I have a binary file that I can send with netcat :
The file contains this:
What I really want to do is send the hex string directly. I’ve tried this:
However, the above command just sends the ascii string directly to nc .
4 Answers 4
I used the -r and -p switches for xxd:
Thanks to inspiration from @Gilles’ answer, here’s a Perl version:
Here a solution without xxd or perl :
If the echo builtin of your shell supports it ( bash and zsh do, but not dash ), you just need to use the right backslash escapes:
If you have /bin/echo from GNU coreutils (nearly standard on Linux systems) or from busybox you can use it, too.
With sed you can generate a escaped pattern:
If you have xxd , that’s easy: it can convert to and from hexadecimal.
I don’t think there’s a reasonable (and reasonably fast) way to convert hexadecimal to binary using only POSIX tools. It can be done fairly easy in Perl. The following script converts hexadecimal to binary, ignoring any input character that isn’t a hexadecimal digit. It complains if an input line contains an odd number of hexadecimal digits.
Источник
How to convert a text file to binary file using linux commands
I have hex code of a binary in text (string) format. How do I convert it to a binary file using linux commands like cat and echo ?
I know command following command with create a binary test.bin. But what if this hexcode is in another .txt file ? How do I «cat» the content of text file to «echo» and generate a binary file ?
# echo -e «\x00\x001» > test.bin
3 Answers 3
use xxd -r . it reverts a hexdump to its binary representation.
Edit: The -p parameter is also very useful. It accepts «plain» hexadecimal values, but ignores whitespace and line changes.
So, if you have a plain text dump like this:
You can convert it to binary with:
And then get useful output with something like:
In addition of xxd , you should also look at the packages/commands od and hexdump . All are similar, however each provide slightly different options that will allow you to tailor the output to your desired needs. For example hexdump -C is the traditional hexdump with associated ASCII translation along side.
If you have long text or text in file you can also use the binmake tool that allows you to describe in text format some binary data and generate a binary file (or output to stdout). It allows to change the endianess and number formats and accepts comments.
Its default format is hexadecimal but not limited to this.
First get and compile binmake:
Источник
Convert binary data to hexadecimal in a shell script
I want to convert binary data to hexadecimal, just that, no fancy formatting and all. hexdump seems too clever, and it «overformats» for me. I want to take x bytes from the /dev/random and pass them on as hexadecimal.
Preferably I’d like to use only standard Linux tools, so that I don’t need to install it on every machine (there are many).
8 Answers 8
Perhaps use xxd :
hexdump and xxd give the results in a different endianness!
With od (GNU systems):
«Depending on your system type, either or both of these two utilities will be available—BSD systems deprecate od for hexdump, GNU systems the reverse.»
Perhaps you could write your own small tool in C, and compile it on-the-fly:
And then feed it from the standard input:
You can even embed this small C program in a shell script using the heredoc syntax.
All the solutions seem to be hard to remember or too complex. I find using printf the shortest one:
But as noted in comments, this is not what author wants, so to be fair, below is the full answer.
. to use above to output actual binary data stream:
- printf ‘%x\n’ . — prints a sequence of integers , i.e. printf ‘%x,’ 1 2 3 , will print 1,2,3,
- $(. ) — this is a way to get output of some shell command and process it
- cat /dev/urandom — it outputs random binary data
- head -c 5 — limits binary data to 5 bytes
- od -An -vtu1 — octal dump command, converts binary to decimal
As a testcase (‘a’ is 61 hex, ‘p’ is 70 hex, . ):
Or to test individual binary bytes, on input let’s give 61 decimal (‘=’ char) to produce binary data ( ‘\\x%x’ format does it). The above command will correctly output 3d (decimal 61):
Источник