I have 2 eight Byte of Data, received as the RX CAN message, so in total 128 bit, but not all the bit carries message. Each byte gives boolean value in specified bit like in the picture. NOTE: This is the structure of first 8 byte, and bit Var Names are not as clean as in the picture.
At the moment I receive 85 bit of message excluding the Reserved bit. Reserved are for the future usage if a message is need to be added.
I have to check the boolean value of the specified bit, and store the boolean value in an Array. I am having difficulty in checking each of 85 bit and storing them in array, is there any more efficient way like using a function to check the bool status, and store the value in array using iteration? or any other,
CodePudding user response:
You could just create a class to store your 8 bytes, and create read only properties to get the different flags, through left shift and bitwise AND. Each flag can return something like this (for example, this is W1_A, bit 0 of first byte):
return (bytes[0] & (1 << 0)) != 0;
So something like this:
public class CanMessage
{
private byte[] _bytes = new byte[8];
public CanMessage(byte[] bytes)
{
if (bytes == null || bytes.Length != 8)
{
throw new ArgumentException(nameof(bytes));
}
_bytes = bytes;
}
public bool W1_A { get { return (_bytes[0] & (1 << 0)) != 0; } }
// ...
}
Which you can then use like this:
var msg = new CanMessage(new byte[] { 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA });
var w1a = msg.W1_A;
CodePudding user response:
Have a look at BitArray, I think it does exactly what you need.
BitArray bitArray = new(inputBytes);
bool set = bitArray.Get(bitIndex);