VB6 整数到两个字节(C 短)通过串行发送

发布于 2024-11-26 23:05:01 字数 183 浏览 1 评论 0原文

我正在扩展一个 VB6 应用程序,该应用程序与小型嵌入式系统通信以使用串行端口(它们当前使用 UDP 广播);因此我试图通过串行模拟 UDP 数据包。

其中一部分包括标头中的消息长度,该长度为两个字节。

如何将 VB6 中的整数转换为两个字节( byte(2) ),以便用 C 编写的接收消息的程序可以将其转换为短整数?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

姐不稀罕 2024-12-03 23:05:01

最简单的方法就是这样做。

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

您可以使用此技术将其他数据类型分解为字节。

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

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
比忠 2024-12-03 23:05:01

由于它将是二进制数据,您应该在字节数组中构建数据包,这样您就可以使用 CopyMemory 从一个位置复制到另一个位置,只需确保使用 htons() 交换字节顺序即可 API 函数。

您还可以使用基本数学来分配每个字节:

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

请记住,正常的网络字节顺序与 Windows(在 x86 和 x64 上)不同,因此最重要的字节首先出现。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文