2

Trying to retrieve data from a device that will send it back to me as mixed ASCII and binary. I can read the ASCII part of the string, but cannot convert the binary into a number (sent as IEEE floating point).

I receive: 6 bytes of ASCII then 5 bytes of binary, with the first binary byte being in integer between 1 and 6 and the following four representing an IEEE floating point number. Ignoring the floating point for now, I am struggling to convert my 7th byte into an integer, having been returned from the control as an ASCII string. If I can get this working a should be able to apply the same principal to the final four bytes to get my floating point number.

I have tried changing the InputMode for the COM control before reading the binary data but this does not seem to work - is this even allowed, I'm not sure.

Any suggestions?

Sam
  • 57
  • 9

2 Answers2

2

Try this: Read the data into a variant as a byte array, then copy the sections separately to different byte arrays. The first segment can be converted to a string using StrConv, and the second to an integer by simple assignment (MyInt = CInt(byt(x)) and the remainder copied to a float using CopyMemory. (If the integer byte is ASCII, then MyInt = Asc(byt(x)) instead.)

Jim Mack
  • 1,070
  • 1
  • 7
  • 16
2

Ok, i guess you can read the ASCII part because you set InputMode = comInputModeText. Instead of that, set InputMode = comInputModeBinary.

As already mentioned in another answer, declare this function:

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByVal Destination As Long, ByVal Source As Long, ByVal Length As Long)

Let say you receive such a buffer as your input:

Dim buf(0 To 10) As Byte

' receiving...

buf(0) = &H62
buf(1) = &H69
buf(2) = &H6E
buf(3) = &H61
buf(4) = &H72
buf(5) = &H79
buf(6) = &H8
buf(7) = &HD0
buf(8) = &HF
buf(9) = &H49
buf(10) = &H40

Your first value is 6 bytes long and you can convert it to a String, your second value is 1 byte long, so you can convert it to a byte (or to Integer or Long, whatever you want). Your tirth value is 4 bytes long, so it will fit in a single.

Dim t as String, b As Byte, s As Single

t = StrConv(LeftB(buf, 6), vbUnicode)
Call CopyMemory(VarPtr(b), VarPtr(buf(6)), 1)
Call CopyMemory(VarPtr(s), VarPtr(buf(7)), 4)
Debug.Print t, b, s ' will print binary 8 3,14159 
deblocker
  • 7,629
  • 2
  • 24
  • 59