I’m looking for a way to encode and decode integers stored in bit fields, IE individual parameters of my messages are encoded as 6 bits, 4 bits, etc in a larger byte array.
Know of any source to make this easy? InsertValueIntoArray/etc. works only on full bytes, I need to decode/encode integers (between 0 and 2^6, of course), into 6 bits in a certain position in a byte array.
Thank you. I don’t have a process for the encoding… I built a CAN receiver, and am receiving messages over the bus I wish to decode. Once I have them decoded, I would like to construct new messages to emulate that device
It’s pretty simple, a sample byte[4] array might break down into:
[unsigned int - 6 bits][unsigned int - 2 bits][unsigned int - 10 bits][unsigned int - 8 bits][unsigned int - 6 bits]
Obviously the range of the first is 0 to 2^6, so it would need to be stored in a byte[], the 10-bit unsigned int in a ushort, etc. I could do this one bit at a time with the applicable math, however I’m sure an existing routine/sources would be far faster, and that could be important
Ah ok, CAN… I have no idea about CAN but here goes:
You have 5 values stored in a 4-byte array. Lets call it MyArray[0-3]. (this has been coded in IE not tested )
val1 = (MyArray[0] & 0xfc) >>2 ; //mask off the first 6 bits only, then shift back to align correctly
val2 = (MyArray[0] & 0x03); //mask off two bits, no shifting required
val3 = (MyArray[1] << 2) | ((MyArray[2] & 0xc0) >>6); // take whole first 8-bit and then next 2 bits
val4 = ((MyArray[2] & 0x3f)<<2) | ((MyArray[3] & 0xc0) >>6); // take 6 bits and then 2 bits
val5 = (MyArray[3] & 0x3f); // take last 6 bits;
Try saying that sentence just before you use the breathalyser project !!
Yes bit manipulation probably does seem strange when you have kilobytes upon kilobytes of storage available - when you need to pack bits into small spots this skill becomes critical, like when you’re pumping bits down a wire like oh a CAN network (apparently )