Dav*_*vid 1 floating-point vba bit-manipulation
如何从Singlevba中的变量中提取位?
例如,我想提取位23到30并将它们放入整数的最低8位.
对于转移的位设置short变量的int,最快的解决方案是一个"快速和肮脏的" CopyMemory的方法,因为看到这里.
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
Run Code Online (Sandbox Code Playgroud)
有关读取和写入整数的单个位,请参见此处.相关的源代码是这样的:
' 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1415 次 |
| 最近记录: |