High and low bytes in VBA

Asked by At

I try to find low/high bytes from a number like that:

If TextBox1.Value <> "" Then
If TextBox1.Value < 65535 Then
Dim lowByte As Byte
Dim highByte As Byte
Dim number As Long
Dim textBoxValueLong As Long
textBoxValueLong = Val(TextBox1.Value)
lowByte = textBoxValueLong And &HFF&
highByte = Fix(textBoxValueLong / 256)
number = highByte * 256 + lowByte
Worksheets(1).Cells(1, 1) = highByte
Worksheets(1).Cells(1, 2) = lowByte
Worksheets(1).Cells(1, 3) = number
End If
End If

But if number is lower than -255, I have an overflow error in this string highByte = Fix(textBoxValueLong / 256)

What is wrong?

UPD: If I use this string: highByte = (textBoxValueI And &HFF00&) / 256, it's ok with dividing into two bytes. But how to merge it rightly? If I use numbers<0 I have an error here: number = highByte * 256 + lowByte

2 Answers

1
tsolina On Best Solutions

declare highBite and lowByte as Long instead, and youll be able to merge them

but for low byte i would suggest to use mod operator

lowByte = textBoxValueLong Mod 256
1
Axel Richter On

If you really need loByte and hiByte as Bytes and must remain within the 2 bytes integer range, then the following should be the solution:

Sub testInteger()

 Dim sTBV As String

 sTBV = "32767"
 'sTBV = "-32768"

 Dim maxI As Integer
 maxI = 127 * 256 + 255
 Dim minI As Integer
 minI = -128 * 256

 If Val(sTBV) >= minI And Val(sTBV) <= maxI Then

  Dim i As Integer
  i = Val(sTBV)

  Dim loByte As Byte, hiByte As Byte

  loByte = i And &HFF&
  hiByte = (i And &HFF00&) / 256

  Dim j As Integer
  j = Val("&H" & Hex(hiByte) & IIf(Len(Hex(loByte)) = 1, "0" & Hex(loByte), Hex(loByte)))

  MsgBox hiByte & ", " & loByte & ", " & j

 Else

  MsgBox "out of integer range"

 End If

End Sub

The 2 bytes integer range is from -32768 to 32767 only.