开发者

Getting and setting single bits in a byte-array using vb.net

I have a byte array with 512 Elements and need to get and set a single bit of a byte in this array.

The operation must not change any other bits, only the specified one.

So if I have a byte like &B00110011 and would like to change the third bit to 1 it should be &B00110111.

Like this:

Dim myarray(511) as byte

myarray(3).2 = 1 ---> This would change the开发者_如何学Go third bit (start counting at 0) of the third byte to 1

I know it should be easily possible using bit-masking but I don't have the time to try for days to get it working.

Thanks for help!!!

Jan


A simple way to do this is using shifts. If you want to set the Nth bit of a number to 1:

mask = 1 << n ' if n is 3, mask results in 00001000
bytevalue = bytevalue or mask

To set a bit as 0:

mask = 255 - (1 << n) ' if n is 3, mask results in 11110111
bytevalue = bytevalue and mask

In both examples, bytevalue is the byte in which you want to alter and mask is also a byte.

EDIT: To retrieve the state of a bit easily is a lot like setting a bit, Where IsSet is a boolean:

mask = 1 << n ' just as above
IsSet = (bytevalue and mask) <> 0


Why don't you use the BitArray class?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜