Posts

Showing posts with the label Binary

Convert A Hex String To Binary And Send With Netcat

Answer : I used the -r and -p switch to xxd : $ echo '0006303030304e43' | xxd -r -p | nc -l localhost 8181 Thanks to inspiration from @Gilles answer, here's a perl version: $ echo '0006303030304e43' | perl -e 'print pack "H*", <STDIN>' | nc -l localhost 8181 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: echo -ne '\x00\x06\x30\x30\x30\x30\x4e\x43' | nc -l localhost 8181 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: $ echo '0006303030304e43' | sed -e 's/../\\x&/g' \x00\x06\x30\x30\x30\x30\x4e\x43 Combined: echo -ne "$(echo '0006303030304e43' | sed -e 's/../\\x&/g')" | nc -l localhost 8181 If you have xxd , that's easy: it can convert to and f...

C Read Binary Stdin

Answer : What you need is freopen() . From the manpage: If filename is a null pointer, the freopen() function shall attempt to change the mode of the stream to that specified by mode, as if the name of the file currently associated with the stream had been used. In this case, the file descriptor associated with the stream need not be closed if the call to freopen() succeeds. It is implementation-defined which changes of mode are permitted (if any), and under what circumstances. Basically, the best you can really do is this: freopen(NULL, "rb", stdin); This will reopen stdin to be the same input stream, but in binary mode. In the normal mode, reading from stdin on Windows will convert \r\n (Windows newline) to the single character ASCII 10. Using the "rb" mode disables this conversion so that you can properly read in binary data. freopen() returns a filehandle, but it's the previous value (before we put it in binary mode), so don't use i...

Convert Binary String To Bytearray In Python 3

Answer : Here's an example of doing it the first way that Patrick mentioned: convert the bitstring to an int and take 8 bits at a time. The natural way to do that generates the bytes in reverse order. To get the bytes back into the proper order I use extended slice notation on the bytearray with a step of -1: b[::-1] . def bitstring_to_bytes(s): v = int(s, 2) b = bytearray() while v: b.append(v & 0xff) v >>= 8 return bytes(b[::-1]) s = "0110100001101001" print(bitstring_to_bytes(s)) Clearly, Patrick's second way is more compact. :) However, there's a better way to do this in Python 3: use the int.to_bytes method: def bitstring_to_bytes(s): return int(s, 2).to_bytes((len(s) + 7) // 8, byteorder='big') If len(s) is guaranteed to be a multiple of 8, then the first arg of .to_bytes can be simplified: return int(s, 2).to_bytes(len(s) // 8, byteorder='big') This will raise OverflowError if len(s) is n...