Main Site Documentation

.NETMF BitConverter equivalent?


#1

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.


#2

isnt this just bit-masking and shifting? Or is your array more complex than that?

give us an example of your array that stores multiple values and it’s structure, and we can show you how to unstuff it.

actually, since you must have a process to stuff the data into the a array, doing the reverse should be relatively simple, no?


#3

Brett,

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 :slight_smile:

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 :slight_smile:


#4

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 :wink: )

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;


#5

And to “muck” i mean simulate those messages, just do similar bit stuffing and shifting, but in reverse… best to protect against over-range values too :slight_smile:

MyArray[0] = ((val1 & 0x3f) <<2 ) | (val2 & 0x03) ;
MyArray[1] = ((val3 & 0x3fc) >> 2);
MyArray[2] = ((val3 & 0x03) << 6) | (val4 & 0x3f);
MyArray[3] = ((val4 & 0x03) <<6 ) | (val5 & 0x3f);


#6

Embedded developers use bit shifting everywhere :slight_smile: windows developer may not know what that is :o


#7

Try saying that sentence just before you use the breathalyser project !! :wink:

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 :slight_smile: )