Click here to Skip to main content
15,915,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello
I am working on code that needs access to bits.

I have an array that gets data from the serial port to variable named "arr".
by the "serialport.read (byte(), int32, int32)" method.

What that I need is access to bits.

For example:
arr(3) gets byte of data contains - (F0)Hex = ("11110000")Bin.
How can I modify the third bit?
11110000

What I have tried:

I have tried to modify the cells by adding another variable of 8 bits and gets the data with index "var(i)"
after I assignment the data to the Var.
Without success.
Posted
Updated 1-Jan-18 21:37pm

If I understand correctly, you have a Byte and want to modify the third bit counting from the left.

This is possible, but you have to know which operation you want to do on the third bit. I can come up with three options: 1) You want to set the bit to 1. 2) You want to set the bit to 0. 3) You want to flip the bit (0 becomes 1 and 1 becomes 0).

If you want to do the first operation (setting the bit to 1), you can do this:
VB.NET
Dim modifier As Byte = 32 ' (00100000)
Dim result As Byte = arr(3) Or modifier
This performs the bitwise OR operation.

If you want to do the second operation (setting the bit to 0), you can do this:
VB.NET
Dim mask As Byte = 223 ' (11011111)
Dim result As Byte = arr(3) And mask
This performs the bitwise AND operation.

If you want to do the third operation (flipping the bit), you can do this:
VB.NET
Dim modifier As Byte = 32 ' (00100000)
Dim result As Byte = arr(3) Xor modifier
This performs the bitwise XOR operation.

To learn more about these bitwise operations, refer to my article: Understand how bitwise operators work (C# and VB.NET examples)[^]
 
Share this answer
 
Look at Logical and Bitwise Operators in Visual Basic | Microsoft Docs[^] - the Bitwise Operators are what you need to look at.
Or allows you to set a bit to one, And with Not lets you reset it to zero.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900