- 3 способа преобразовать hex в бинарный код на bash
- convert a hex string to binary and send with netcat
- 4 Answers 4
- Converting from binary to hex and back
- 3 Answers 3
- Converting from hex to bin ( hex2bin ):
- Converting from bin to hex ( bin2hex ):
- Example use:
- Converting from *.hex to *.bin for ARM on Linux
- 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
Источник
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.
Источник
Converting from binary to hex and back
Given a binary file, how do you convert it to a hex string and back, using only standard tools like sed and cut , on a minimal system with busybox installed?
These tools are not available:
A hexdump command comes with busybox , but it is different from the one that comes with util-linux .
I’m looking for a script or command to convert a file to a hex string, and a corresponding one for converting it back to binary. The intermediate format doesn’t have to be hex, it can be base64 or something else.
This is for an embedded device with limited disk space.
3 Answers 3
Here’s what I came up with (based on several online sources and some experimentation).
Converting from hex to bin ( hex2bin ):
Converting from bin to hex ( bin2hex ):
Example use:
This works with busybox, but hex2bin is unfortunately limited by the maximum length of the argument given to xargs , so this method will only work for small files (less than 32 KiB on my desktop system).
POSIXly (and only using a common subset compatible with busybox (or at least the busybox as built for the current busybox Debian package):
(one hex per line)
If your busybox , contrary to Debian’s one has been built without the DESKTOP option, then the -An and -tx1 option to od won’t be available. You can use od -b instead which will give a one-byte octal dump with octal offsets. od -b is Unix but not POSIX however so won’t work on every Unix-like system.
bin2hex would become:
Again, tested only with Debian’s busybox, I can’t tell how much of that is dependant on some busybox compile-time option or another. You’d have to test on the target system.
Источник
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 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):
Источник