Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What data type should you use in C++ when working with binary data blocks?

Tags:

c++

While string should be used for working with strings, I would like to know what structure you should use in C++ when working with blocks of data.

I'm asking this because it would be nicer to use one parameter instead of passing a char* data and size_t size (or a custom structure).

like image 297
bogdan Avatar asked Feb 11 '12 18:02

bogdan


People also ask

What are binary files in C?

Binary fileIt contains 1's and 0's, which are easily understood by computers. The error in a binary file corrupts the file and is not easy to detect. In binary file, the integer value 1245 will occupy 2 bytes in memory and in file. A binary file always needs a matching software to read or write it.

What operations that can be performed on binary files in C?

Read, write and seek operations can be performed on binary files with the help of fread(), fwrite() and fseek() functions, respectively. After reading or writing a structure, the file pointer is moved to the next structure. The fseek() function can move the pointer to the position as requested.

Is binary a type of data?

Binary data is a type of data that is represented or displayed in the binary numeral system. Binary data is the only category of data that can be directly understood and executed by a computer. It is numerically represented by a combination of zeros and ones.

Is there a binary data type in C++?

int is the integer data type. Integers are represented in binary format. Binary numbers may be stored in either 1's or 2's complement form. Most machines use 2' complement.


3 Answers

std::vector<unsigned char>

or, preferably,

std::vector<std::uint8_t>

(In C++11, uint8_t can be found in <cinttypes>. Older compilers, but not MSVC, may have the C99 header <inttypes.h>. If your data is a sequence of 16-bit units, use uint16_t etc.)

If the size of the data blocks is known at compile time, std::array is appropriate; it wastes less space than vector.

like image 74
Fred Foo Avatar answered Oct 18 '22 03:10

Fred Foo


There are a number of containers in the STL, not only vector. Look and choose what fits your situation.

like image 24
mikithskegg Avatar answered Oct 18 '22 01:10

mikithskegg


The above solutions is good, but consider this solution may be good :

  1. bitset in STL
  2. bit_vector in SGI
  3. qbitarray in QTL
like image 2
softghost Avatar answered Oct 18 '22 01:10

softghost