Read specific bytes of a file

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); }

C++ int to byte array

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

Ruby: create a String from bytes

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.

How to split a byte string into separate parts

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

Convert bytes to bits in python

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

Appending a byte[] to the end of another byte[] [duplicate]

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