1

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

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this sounds easy. And how to GET the state easily?
The function to get the state is not right. ... !=0 is not possible in vb.net. Using <> 0 returns -1 on a bit that is set. Would you please correct it.
@user831915: sorry, I don't work in VB at all anymore. I detest the language, but bitmasks and such are a fun subject to talk about.
1

Why don't you use the BitArray class?

1 Comment

You could, but the values are not single bit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.