Bitfield access to array
-
I have an fixed length array :- Byte[] myArray = new Byte[50]; Now this represents a specific message structure. For example, the sort of thing I want to do is : 1. to read and set a bit field, Byte[25], bit 1 2. to read and set a 5 bit value, Byte[20], bits 0-5 3. to read and set a 32 bit number, Byte[10] These are just a few examples of what functions I want to perform on the array. But they highlight some of my challanges. Any thoughts on gneral ways to achieve this? Thanks, Liam
-
I have an fixed length array :- Byte[] myArray = new Byte[50]; Now this represents a specific message structure. For example, the sort of thing I want to do is : 1. to read and set a bit field, Byte[25], bit 1 2. to read and set a 5 bit value, Byte[20], bits 0-5 3. to read and set a 32 bit number, Byte[10] These are just a few examples of what functions I want to perform on the array. But they highlight some of my challanges. Any thoughts on gneral ways to achieve this? Thanks, Liam
Well, to set a particular bit in a byte, I would use bitwise operators. The exclusive-or (^) would work:
byte b = 35;
b ^= 0x01;*Note - This will change the value of the bit. If it's 0, it will be changed to 1, if it's 1 it will be changed to zero. Of course, it's hard to tell what you mean by bit 1. But to set a particular bit in the byte array is not much different:
byte[] b = new byte[50];
...
b[25] ^= 0x01;To read the value, you can use a bitwise-and ( & ) :
if (b[20] & 0x1f == a) { ... }
I'm not sure what you mean by setting a 32 bit number on a single byte though.
Last modified: Friday, July 28, 2006 9:43:29 AM --