0

我对VB6非常不熟悉,所以请原谅菜鸟问题:

我正在尝试将 long 转换为它的组件字节。在 C 中,由于自动截断和位移运算符,它很简单。对于我的生活,我无法弄清楚如何在 VB6 中做到这一点。

到目前为止的尝试通常看起来都是这样的

sys1 = CByte(((sys & &HFF000000) / 16777216))   ' >> 24
sys2 = CByte(((sys & &HFF0000) / 65536))      ' >> 16 

sys1 和 sys2 被声明为Bytesys 被声明为Long

尝试执行此操作时出现类型不匹配异常。有人知道如何将 a 转换Long为 4 Bytes 吗?

谢谢

4

3 回答 3

4

您正确划分,但您忘记仅屏蔽最低有效位。

提供要划分为字节的单词和索引(0 是最不重要的,1 是下一个,等等)

Private Function getByte(word As Long, index As Integer) As Byte
    Dim lTemp As Long
    ' shift the desired bits to the 8 least significant
    lTemp = word / (2 ^ (index * 8))
    ' perform a bit-mask to keep only the 8 least significant
    lTemp = lTemp And 255
    getByte = lTemp
End Function
于 2013-03-05T23:50:40.537 回答
1

FreeVBCode.com上找到。未测试,抱歉。

Option Explicit

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

Public Function LongToByteArray(ByVal lng as Long) as Byte()

'Example:
'dim bytArr() as Byte
'dim iCtr as Integer
'bytArr = LongToByteArray(90121)
'For iCtr = 0 to Ubound(bytArr)
   'Debug.Print bytArr(iCtr)
'Next
'******************************************
Dim ByteArray(0 to 3)as Byte
CopyMemory ByteArray(0), Byval VarPtr(Lng),Len(Lng) 
LongToByteArray = ByteArray

End Function
于 2013-03-05T20:36:50.590 回答
0

您可以通过结合 UDT 和LSet语句在简单值类型和字节数组之间进行转换。

Option Explicit

Private Type DataBytes
    Bytes(3) As Byte
End Type

Private Type DataLong
    Long As Long
End Type

Private DB As DataBytes
Private DL As DataLong

Private Sub cmdBytesToLong_Click()
    Dim I As Integer

    For I = 0 To 3
        DB.Bytes(I) = CByte("&H" & txtBytes(I).Text)
    Next
    LSet DL = DB
    txtLong.Text = CStr(DL.Long)

    txtBytes(0).SetFocus
End Sub

Private Sub cmdLongToBytes_Click()
    Dim I As Integer

    DL.Long = CLng(txtLong.Text)
    LSet DB = DL
    For I = 0 To 3
        txtBytes(I).Text = Right$("0" & Hex$(DB.Bytes(I)), 2)
    Next

    txtLong.SetFocus
End Sub
于 2013-03-05T22:50:10.617 回答