Byte to Binary String C# – Display all 8 digits
Convert.ToString(MyVeryOwnByte, 2).PadLeft(8, ‘0’); This will fill the empty space to the left with ‘0’ for a total of 8 characters in the string
Convert.ToString(MyVeryOwnByte, 2).PadLeft(8, ‘0’); This will fill the empty space to the left with ‘0’ for a total of 8 characters in the string
Create a BinaryReader, read 10 bytes starting at byte 50: byte[] test = new byte[10]; using (BinaryReader reader = new BinaryReader(new FileStream(file, FileMode.Open))) { reader.BaseStream.Seek(50, SeekOrigin.Begin); reader.Read(test, 0, 10); }
You don’t need a whole function for this; a simple cast will suffice: int x; static_cast<char*>(static_cast<void*>(&x)); Any object in C++ can be reinterpreted as an array of bytes. If you want to actually make a copy of the bytes into a separate array, you can use std::copy: int x; char bytes[sizeof x]; std::copy(static_cast<const char*>(static_cast<const void*>(&x)), … Read more
The code below will work on both Python 2.7 and 3: from base64 import b64encode from os import urandom random_bytes = urandom(64) token = b64encode(random_bytes).decode(‘utf-8’)
There is a much simpler approach than any of the above: Array#pack: >> [65,66,67,68,69].pack(‘c*’) => “ABCDE” I believe pack is implemented in c in matz ruby, so it also will be considerably faster with very large arrays. Also, pack can correctly handle UTF-8 using the ‘U*’ template.
Read the bits from a file, low bits first. def bits(f): bytes = (ord(b) for b in f.read()) for b in bytes: for i in xrange(8): yield (b >> i) & 1 for b in bits(open(‘binary-file.bin’, ‘r’)): print b
You can use slicing on byte objects: >>> value = b’\x00\x01\x00\x02\x00\x03′ >>> value[:2] b’\x00\x01′ >>> value[2:4] b’\x00\x02′ >>> value[-2:] b’\x00\x03′ When handling these frames, however, you probably also want to know about memoryview() objects; these let you interpret the bytes as C datatypes without any extra work on your part, simply by casting a ‘view’ … Read more
Another way to do this is by using the bitstring module: >>> from bitstring import BitArray >>> input_str=”0xff” >>> c = BitArray(hex=input_str) >>> c.bin ‘0b11111111’ And if you need to strip the leading 0b: >>> c.bin[2:] ‘11111111’ The bitstring module isn’t a requirement, as jcollado‘s answer shows, but it has lots of performant methods for … Read more
Using System.arraycopy(), something like the following should work: // create a destination array that is the size of the two arrays byte[] destination = new byte[ciphertext.length + mac.length]; // copy ciphertext into start of destination (from pos 0, copy ciphertext.length bytes) System.arraycopy(ciphertext, 0, destination, 0, ciphertext.length); // copy mac into end of destination (from pos … Read more
int x = (number >> (8*n)) & 0xff; where n is 0 for the first byte, 1 for the second byte, etc.