在VBA中从IEEE-754 double中提取尾数,指数和符号数据 [英] Extract mantissa, exponent and sign data from IEEE-754 double in VBA

查看:197
本文介绍了在VBA中从IEEE-754 double中提取尾数,指数和符号数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从VBA中的IEEE-754 64位(双)浮点数中提取尾数,指数和符号数据?谢谢

How to extract mantissa, exponent and sign data from an IEEE-754 64-bit (double) floating-point number in VBA? Thanks

编辑(在John Coleman评论之后).在发布原始问题之前,我到处寻找解决方案,并且只能找到如何在C语言中执行此操作(例如,使用具有位字段的结构).无法为VBA找到任何东西.我曾尝试使用VBA的位运算符(即AND,OR,NOT,XOR),但这似乎无法提供预期的结果.例如,以单精度IEEE 32位浮点表示的1表示为

Edit (after John Coleman comments). Before posting the original question, I have looked around for a solution and could only find how to do it in C (e.g. using structures with bit fields). Couldn't find anything for VBA. I have tried using VBA's bit operators (i.e. AND, OR, NOT, XOR) but this does not seem to give the expected result. For example, 1 expressed in single precision IEEE 32-bit floating-point is represented by

其中第一位用于符号,后8位用于(有偏的)指数,最后23位用于尾数.将NOT应用于1应该返回

where the first bit is for sign, the next 8 bits are for the (biased) exponent, and the last 23 bits are for the mantissa. Applying NOT to 1 should return

十进制为-3.9999998,但VBA中的以下代码返回-2,由

which is -3.9999998 in decimal, but the following code in VBA returns -2, which is represented by

x = Not 1!
Debug.Print x

我看不到要在我的OP中发布此内容的问题.

I didn't see the point of posting this in my OP.

推荐答案

我想我已经找到了解决方法.以下函数DoubleToBin返回代表IEEE-754双浮点数的64位字符串.通过将LSet与相同大小的用户定义类型结合使用,它使用VBA技巧"来传递原始数据,而无需使用API​​例程(例如MemCopy(RtlMoveMemory)).一旦有了位串,就可以从中提取所有分量.

I think I've found the way to do this. The following function DoubleToBin returns a string of 64 bits representing an IEEE-754 double floating-point number. It uses a VBA "trick" to pass around raw data without using API routines (such as MemCopy (RtlMoveMemory)) by combining LSet with User Defined Types of the same size. And once we have the bit string we can extract all components from it.

Type TDouble
  Value As Double
End Type

Type TArray
  Value(1 To 8) As Byte
End Type

Function DoubleToArray(DPFloat As Double) As Variant
  Dim A As TDouble
  Dim B As TArray
  A.Value = DPFloat 
  LSet B = A
  DoubleToArray = B.Value
End Function

Function DoubleToBin(DPFloat As Double) As String
  Dim ByteArray() As Byte
  Dim BitString As String
  Dim i As Integer
  Dim j As Integer

  ByteArray = DoubleToArray(DPFloat)

  For i = 8 To 1 Step -1
    j = 2 ^ 7
    Do While j >= 1
      If (ByteArray(i) And j) = 0 Then
        BitString = BitString & "0"
      Else
        BitString = BitString & "1"
      End If
      j = j \ 2
    Loop
  Next i

  DoubleToBin = BitString
End Function

它在这里如何工作-我现在接受我自己的答案了吗?

How does it work on here - do I now accept my own answer?

这篇关于在VBA中从IEEE-754 double中提取尾数,指数和符号数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆