如何把一个 Long 型转换成 Byte(0 to 3)?
发布网友
发布时间:2022-05-16 18:25
我来回答
共4个回答
热心网友
时间:2023-11-18 13:01
借助calling_1的代码:
Option Explicit
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Dim Buffer(3) As Byte
Private Sub Command1_Click() '获得Long数据的4个Byte值
Dim i As Integer
Dim a As Long
a = Val(Text1)
CopyMemory Buffer(0), a, 4
For i = 0 To 3
Print Buffer(i)
Next
End Sub
Private Sub Command2_Click()
Dim l_byte(0 To 3) As Byte '要被转化的Byte()
Dim l_long As Long '要保存转化的Long
l_byte(0) = Buffer(3)
l_byte(1) = Buffer(2)
l_byte(2) = Buffer(1)
l_byte(3) = Buffer(0)
l_long = "&H" & (CStr(Hex(l_byte(0))) & CStr(Hex(l_byte(1)))) & CStr(Hex(l_byte(2))) & CStr(Hex(l_byte(3)))
Text2 = l_long
End Sub
Private Sub Form_Load()
Text1 = ""
Text2 = ""
End Sub
热心网友
时间:2023-11-18 13:02
是的,用CopyMemory就可以实现
热心网友
时间:2023-11-18 13:02
1.LONG变为bYTE(0 to 3):
Dim l_strTemp As String
Dim l_byte(0 To 3) As Byte '要保存转化的Byte数组
Dim l_long As Long
l_long = &HABCD1234 '要被转化的Long
If l_long >= 0 Then 'VB中,long的范围是-'&h7fffffff到&h7fffffff,当l_long大于&h7fffffff时会被
'表示为负数,因此特殊处理(转化为字符串并取前两位)
l_byte(0) = (l_long And &HFF000000) / &H1000000
Else
l_strTemp = CStr(Hex(l_long))
l_byte(0) = CByte("&H" & Left(l_strTemp, 2))
End If
l_byte(1) = (l_long And &HFF0000) / &H10000 '其他的正常处理
l_byte(2) = (l_long And &HFF00&) / &H100&
l_byte(3) = l_long And &HFF
------------------------------------------------------
2.bYTE(0 to 3)变为long:
Dim l_byte(0 To 3) As Byte '要被转化的Byte()
Dim l_long As Long '要保存转化的Long
l_byte(0) = &H12
l_byte(1) = &H56
l_byte(2) = &HAB
l_byte(3) = &HCD
l_long = "&H" & (CStr(Hex(l_byte(0))) & CStr(Hex(l_byte(1)))) & CStr(Hex(l_byte(2))) & CStr(Hex(l_byte(3)))
热心网友
时间:2023-11-18 13:03
一个*的方法:开个二进制临时文件,然后把long写进去,再按照byte数组读出。反之亦然。
这个方法效率有些低,不要用在追求速度的场合。偶尔用用还可以。