开发者

VB6 integer to two bytes (C short) to send over serial

I'm expanding a VB6 application which communicates with开发者_运维百科 small embedded systems to use the serial port (they currently use UDP broadcasts); and thus am trying to emulate UDP packets over serial.

Part of this includes a message length in the header, which is two bytes long.

How can I convert an integer in VB6 to two bytes ( byte(2) ) so that program written in C that picks up the message can cast it to a short integer?


The easiest way is to do this.

Private Type IntByte
    H As Byte
    L As Byte
End Type


Private Type IntType
    I As Integer
End Type

Public Sub Convert(ByVal I as Integer, ByRef H as Byte, ByRef L as Byte)

  Dim TempIT As IntType
  Dim TempIB As IntByte

 TempIT.I = I

  LSet TempIB = TempIT

  H = TempIT.H
  L = TempIT.L

End Sub

You can use this technique to break up other data types into bytes.

Private Type LongByte
    H1 As Byte
    H2 As Byte
    L1 As Byte
    L2 As Byte
End Type

Private Type DblByte
    H1 As Byte
    H2 As Byte
    H3 As Byte
    H4 As Byte
    L1 As Byte
    L2 As Byte
    L3 As Byte
    L4 As Byte
End Type


Seeing as it'll be binary data, you should be building the packet in a byte array so you can just use CopyMemory to copy from one location to the other, just make sure you swap the byte order using the htons() API function.

You can also use basic maths to assign each byte:

byte0 = (value And &H0000FF00&) / &H100
byte1 = (value And &H000000FF&)

Remember the normal network byte order is different to Windows (on x86 and x64) so the most significant byte goes first.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜