setting bits in a byte?

techknight

Well-Known Member
Licensed User
Longtime User
How do you set specific bits in a byte? I have a variable declared as a byte and i want to be able to set specific bits in that byte.
 

sorex

Expert
Licensed User
Longtime User
check for and() and or() or just a plain addition (+) would do aswell to set some specific bit(s)
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Here:
B4X:
Dim b As Byte
b = 23
LogByte(b)
b = SetBit(b, 7, True)
LogByte(b)
b = SetBit(b, 0, False)
LogByte(b)


Sub LogByte(b As Byte)
   Log(NumberFormat2(Bit.ToBinaryString(Bit.And(0xff, b)), 8, 0, 0, False))
End Sub
Sub SetBit(b As Byte, index As Int, on As Boolean) As Byte
   If on Then
      Return Bit.Or(b, Bit.ShiftLeft(1, index))
   Else
      Return Bit.And(b, Bit.Not(Bit.ShiftLeft(1, index)))
   End If
End Sub
 
Upvote 0
Top