从VBA中的浮点中提取位 [英] Extracting bits from a float in vba

查看:132
本文介绍了从VBA中的浮点中提取位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从vba中的 Single 变量中提取位?

How can I extract the bits from a Single variable in vba?

例如,我要提取第23至30位并将其放入整数的最低8位.

For example, I want to extract bits 23 to 30 and place them into the lowest 8 bits of an integer.

推荐答案

为了将 short 变量的位设置传输到 int ,最快的解决方案是快速而肮脏的" CopyMemory方法,如

For transferring the bit settings of the short variable to an int, the fastest solution is a 'quick and dirty' CopyMemory approach, as seen here.

Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Bytes As Long)

Public Sub DoubleToIEEE32(ByVal dValue As Double, ByRef nI1 As Integer, ByRef nI2 As Integer)
  Dim fValue As Single
  Dim nInt(1) As Integer

  fValue = CSng(dValue)
  CopyMemory nInt(0), fValue, Len(fValue) ‘ copy from Single to Int Array

  ‘ Internally, the Low Word is word 1 and High Word is word 2.
  ‘ Swap them to make it like the PLC guys do it.
  nI1 = nInt(1)
  nI2 = nInt(0)
End Sub

有关以整数形式读取和写入单个位的信息,请参见此处.相关的源代码是这样的:

For reading and writing single bits in integers, see here. The relevant source code is this:

' The ClearBit Sub clears the nth bit (Bit%) 
' of an integer (Byte%).
Sub ClearBit (Byte%, Bit%)
   ' Create a bitmask with the 2 to the nth power bit set:
   Mask% = 2 ^ Bit%
   ' Clear the nth Bit:
   Byte% = Byte% And Not Mask%
End Sub

' The ExamineBit function will return True or False depending on
' the value of the nth bit (Bit%) of an integer (Byte%).
Function ExamineBit% (Byte%, Bit%)
   ' Create a bitmask with the 2 to the nth power bit set:
   Mask% = 2 ^ Bit%
   ' Return the truth state of the 2 to the nth power bit:
   ExamineBit% = ((Byte% And Mask%) > 0)
End Function

' The SetBit Sub will set the nth bit (Bit%) of an integer (Byte%).
Sub SetBit (Byte%, Bit%)
   ' Create a bitmask with the 2 to the nth power bit set:
   Mask% = 2 ^ Bit%
   ' Set the nth Bit:
   Byte% = Byte% Or Mask%
End Sub

' The ToggleBit Sub will change the state of the 
' nth bit (Bit%) of an integer (Byte%).
Sub ToggleBit (Byte%, Bit%)
   ' Create a bitmask with the 2 to the nth power bit set:
   Mask% = 2 ^ Bit%
   ' Toggle the nth Bit:
   Byte% = Byte% Xor Mask%
End Sub

这篇关于从VBA中的浮点中提取位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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