Byte Variables

JSolum

New Member
Licensed User
Longtime User
:sign0104:

I am working on a simple program that will send, 4 bytes to a microcontroller over bluetooth. There is a sync byte (always 251), a command byte (cmd) 0-255, the inverse of cmd, and cmd with the bit order reversed. I have listed part of the code that sends the bytes below:

B4X:
Sub btnSend_Click

   Timer1.Enabled = False
   
   Dim cmd As Byte  'For testing... "cmd" will come from
   cmd = 179        ' another section of code.
   
   Dim Xmit(4) As Byte  
      Xmit(0) = 251    'Sync Byte
      Xmit(1) = cmd  'Command Byte
      Xmit(2) = Bit.Not(cmd)    'Inverse of Command Byte
      Xmit(3) = 0       'Need to zero?
   
      Dim BitVal As Byte
      Dim temp As Byte
         temp = cmd
      
   For i = 7 To 0 Step -1            'Routine to reverse bit order of cmd
      BitVal = Bit.AND(temp, 0x01)   'Isolates current low bit
      Xmit(3) = Xmit(3) + (BitVal * Power(2,i)) 'Rebuild Xmit(3) in reverse order
      temp = Bit.UnsignedShiftRight(temp,1)  'Move next lowest bit
   Next

   AStream.Write(Xmit)
   
   Timer1.Enabled = True
   
End Sub

While the code works, and I get what I expect at the receiving end, I don't have the "warm fuzzies" that I have coded it correctly. Here are my questions:

1. The "bitwise related methods" use "Int" variables and I am using them with "Byte" variables, such as "Xmit(2) = Bit.Not(cmd)" where Xmit(2) and cmd are bytes.The code appears to work. Is this because "Byte" is a type of Int?

2. Is a newly declared variable always 0 or should you clear it to be sure?

3. Is there a more eligant way to reverse the bits in a byte than the routine that I have used?

Thank you!

Jim
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
1. Byte is a different type than Int. Ints are made of 4 Bytes. When you set an Int to a Byte then the byte value will be the value of the least significant byte.

2. Yes.

This code which is similar to yours might be helpful:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   For i = -128 To 127
      Dim b As Byte = i
      Log(ByteToString(b))
      Log(ByteToString(Reverse(b)))
      Log("****")
   Next
End Sub

Sub ByteToString(b As Byte) As String
   Return NumberFormat2(Bit.ToBinaryString(Bit.AND(b, 0x00FF)), 8, 0, 0, False)
End Sub

Sub Reverse(b As Byte) As Byte
   Dim r As Byte
   For i = 0 To 7
      'get the bit at i:
      Dim bt As Byte = Bit.UnsignedShiftRight(Bit.AND(b, Bit.ShiftLeft(1, i)), i)
      r = Bit.OR(r, Bit.ShiftLeft(bt, 7 - i))
   Next
   Return r
End Sub
 
Upvote 0
Top