This question has already been answered:

Help me figure out what it means

:

In the variable below I will give the structure in C ++ Builder:

typedef struct { unsigned int nr:8; // unsigned int y:8; // 1 unsigned int sm:3; // 2 unsigned int d:5; // 3 unsigned int m:4; // 4 unsigned int r:4; // 5 } n_def; 

What exactly is the number after? nr:8 or 3 or 5 ..... etc? And how to implement the same thing in C #?

The fact is that I need to read data from a binary file, and how do I understand, first I need to read the entire block and then break it into bits? in C #, reading is as follows:

  using (BinaryReader reader = new BinaryReader(File.Open(path, FileMode.Open))) { // пока не достигнут конец файла // считываем каждое значение из файла while (reader.PeekChar() > -1) { int numb = reader.ReadInt32(); uint nr = reader.ReadUInt32(); // переменная которую нужно разбить на биты } } 

I understood correctly? how to properly implement? can better use marshaling? thank you for your responses

Reported as a duplicate by the participants αλεχολυτ , Qwertiy , VladD c # Dec 28 '16 at 16:58 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

1 answer 1

The colon is used to specify the size of the variable in bits. Such a record works only inside structures, where several small values ​​of 2 or 3 bits can be merged into one 16, 32 or 64-bit integer variable.

In your example, all variables will fit into a 32-bit integer. In reality, this will be a single integer variable, and the compiler will generate a code for you to access individual bits.

In C #, as in C ++, instead of such a record, direct bit manipulation is often used. For example, to highlight three bits, starting with the fifth, you do this:

 var y = (x >> 4) & 0x07; 

First, you shift the number 4 bits to the right, losing the lower 4 bits. Then apply the mask 00000111 2 , erasing the high 5 bits and leaving the low 3. As a result, you get three bits: the fifth, sixth and seventh.

To set these bits, you can erase them first, and then apply the OR operation:

 var y = (y & 0x8F) | (x << 4); 

Here 0x8F is 10001111 2 , and x contains the new value for these 3 bits.

However, in C # there is a BitVerctor32 structure that will help you work with individual bits or groups of bits.

  • In addition to BitVector32 in C #, you can also use [Flags] enum - msdn.microsoft.com/ru-ru/library/cc138362.aspx Of course, not the equivalent of bit fields, but maybe somewhere it will be convenient, including in conjunction with the proposed approach . - paulgri