是否有 VB 函数将 32 位浮点数转换为小端十六进制

Is there a VB function to convert 32 bit float to little endian hex

如图所示:https://gregstoll.com/~gregstoll/floattohex/ 我需要将 32 位浮点数转换为小端十六进制(在转换前单击交换结束按钮)。我在 python 中通过转换为大端然后重新排序成功地做到了这一点,但我不知道如何在 VB 中解决这个问题,因为我对这种语言完全陌生。使用十六进制内置函数 returns 19a,我认为这意味着它没有正确地将我的输入评估为单个输入。

我在这里找到了推荐的解决方案,但无法正常工作: https://www.tek-tips.com/faqs.cfm?fid=6404

任何建议都很好,提前致谢。

有多种方法可以做到这一点 - 最明显的是复制内存 API。前段时间,这里发布了一个非常简洁的解决方案:Extracting bits from a float in vba 避免了对 API

的需要

基本上,您只需要几个简短的函数:

Option Explicit

Type SingleType
  Value As Single
End Type
Type FourBytesType
  Value(3) As Byte
End Type

Private Function SingleToBytes(f As Single) As Variant
    Dim sngType As SingleType
    Dim bytesType As FourBytesType
    
    sngType.Value = f
    LSet bytesType = sngType
    SingleToBytes = bytesType.Value
End Function

Private Function BytesToHex(bytes As Variant) As String
    Dim result As String
    Dim i As Long
    
    For i = LBound(bytes) To UBound(bytes)
        result = result & IIf(bytes(i) < 16, "0", "") & Hex(bytes(i))
    Next
    BytesToHex = result
    
End Function

如果您想测试字节顺序并反转数组,则可以添加类似以下的使用字节顺序标记的内容。我还没有在大端处理器上测试过它,但我认为它可以工作:

Private Function IsLittleEndianProcessor() As Boolean
    Const BOM As Single = 1
    Const MSB As Byte = 63
    Dim bytes() As Byte
    Dim n As Long
    
    bytes = SingleToBytes(BOM)
    n = UBound(bytes)
    IsLittleEndianProcessor = (bytes(n) = MSB)
    
End Function

Private Function ChangeEndianness(bytes As Variant) As Variant
    Dim result() As Byte
    Dim n As Long, m As Long
    
    ReDim result(UBound(bytes))
    m = UBound(bytes)
    For n = LBound(bytes) To UBound(bytes)
        result(m) = bytes(n)
        m = m - 1
    Next
    
    ChangeEndianness = result
End Function

我实际上不确定您希望如何显示十六进制字符串,但如果需要,您可以通过数组向后退一步以写入十六进制。样本测试将是:

Public Sub TestMe()
    Dim bytes As Variant
    Dim output As String
    
    bytes = SingleToBytes(3.1415)
    
    If Not IsLittleEndianProcessor Then
        bytes = ChangeEndianness(bytes)
    End If
    output = BytesToHex(bytes)
    Debug.Print output
    
End Sub