我需要一个函数,将值作为字节,起始位置作为整数,并返回 1 或 0 作为无符号字节,具体取决于相应位是 1 还是 0。
示例1:
十进制 100 是二进制 0110 0100。如果起始位置(索引)是 1(从左数),我预计返回 1,因为 0110 0100。
示例2:
如果起始位置为 0,我预计返回 0,因为 0110 0100。
我还需要将相同的原理应用于采用字节数组的函数。
我当前的问题是函数返回错误的结果。提供的位置偏离了 1。我知道这是错误,因为我测试了这个直到位置 4。我可以简单地写
(pos-1)
来修复它,但也许你有更好的解决方案。
在带有数组的函数中,当前代码中包含 204,因为我从 C++ 解决方案中改编了该函数,它故意读取超出数组边界的内容而不引发异常。在调试模式下,无论我多久重新启动一次电脑,我都会看到 204。
我需要VB.NET中的这个功能。这是我目前的尝试:
Option Strict On
Module Module1
Sub Main()
Dim result1 As Byte = GetBitByPos(100, 0)
Dim result2 As Byte = GetBitByPos(100, 1)
Dim result3 As Byte = GetBitByPosArray({100}, 0)
Dim result4 As Byte = GetBitByPosArray({100}, 1)
End Sub
Private Function GetBitByPos(value As Byte, pos As Integer) As Byte
Return CByte(value >> (8 - pos Mod 8) And &H1)
End Function
Private Function GetBitByPosArray(buffer As Byte(), pos As Integer) As Byte
If pos \ 8 >= buffer.Length Then
Return CByte(204 >> (8 - pos Mod 8) And &H1)
End If
Return CByte(buffer(pos \ 8) >> (8 - pos Mod 8) And &H1)
End Function
End Module
你可以试试这个。 它适用于所有整数值类型。
''' <summary>
''' determine if bit is on or off
''' </summary>
''' <param name="value">the value to check</param>
''' <param name="position">which position(from left), 63 - 0</param>
''' <returns>true if on</returns>
''' <remarks></remarks>
Private Function IsBitAtPositionOn(value As Int64,
position As Integer) As Boolean
Dim rv As Boolean = False
Dim whBit As Long = 1L << (63 - position)
If (value And whBit) = whBit Then
rv = True
End If
Return rv
End Function
''' <summary>
''' determine if bit is on or off
''' </summary>
''' <param name="value">the value to check</param>
''' <param name="position">which position(from left), 31 - 0</param>
''' <returns>true if on</returns>
''' <remarks></remarks>
Private Function IsBitAtPositionOn(value As Int32,
position As Integer) As Boolean
Dim L As Long = value
L = L << 32 'position
Return IsBitAtPositionOn(L, position)
End Function
''' <summary>
''' determine if bit is on or off
''' </summary>
''' <param name="value">the value to check</param>
''' <param name="position">which position(from left), 15 - 0</param>
''' <returns>true if on</returns>
''' <remarks></remarks>
Private Function IsBitAtPositionOn(value As Int16,
position As Integer) As Boolean
Dim L As Long = value
L = L << 48 'position
Return IsBitAtPositionOn(L, position)
End Function
''' <summary>
''' determine if bit is on or off
''' </summary>
''' <param name="value">the value to check</param>
''' <param name="position">which position(from left), 7 - 0</param>
''' <returns>true if on</returns>
''' <remarks></remarks>
Private Function IsBitAtPositionOn(value As Byte,
position As Integer) As Boolean
Dim L As Long = value
L = L << 56 'position
Return IsBitAtPositionOn(L, position)
End Function