How to create a char array from bit information using C #

I have the following structure:

enter image description here

I need to create a char array with informational values, I mean, I need something like this:

char[] result = new char[]{Information, Information, Information, Information}

What is the best way to do this? I do this by receiving bytes, then transferring them to bitmaps, then creating a string with informational positions and finally applying the ToCharArray () method to the string with the required information, but I want to know if there is a better way to do this.

var oneByteInfo = message.ReadBytes(1);
var oneByteInfo2 = message.ReadBytes(1);
var infoBitArray = new BitArray(oneByteInfo);
var info2BitArray = new BitArray(oneByteInfo2);

var arrayString = Convert.ToString(BitConverter.GetBytes(infoBitArray[0])[0]) +  
                            Convert.ToString(BitConverter.GetBytes(infoBitArray[1])[0]) + 
                            Convert.ToString(BitConverter.GetBytes(info2BitArray[0])[0]) + 
                             Convert.ToString(BitConverter.GetBytes(info2BitArray[1])[0]);

var result = arrayString.ToCharArray();

Thanks in advance.

+4
source share
1 answer

supposedly something like:

char[] arr = new char[4];
arr[0] = (bytes[2] & 0x01) != 0 ? '1' : '0';
arr[1] = (bytes[2] & 0x02) != 0 ? '1' : '0';
arr[2] = (bytes[3] & 0x01) != 0 ? '1' : '0';
arr[3] = (bytes[3] & 0x02) != 0 ? '1' : '0';

Note that there are ways to do this more simply (having, for example, all 4 possible combinations of two bits as strings and just doing a search), but this works in the general case.

+2
source

Source: https://habr.com/ru/post/1692635/


All Articles