I have written a function in VB.Net (.NET Framework 4.8) that reads a specific number of bits from a byte array starting from a given position and sums the result. Example:NextBits({255, 255, 255}, 0, 24)
returns 765 because 255 + 255 + 255.
If a few bits are read and these cross a byte boundary, then a new byte is returned with the specified bits as the most significant bits. Example:NextBits({0, 15, 200}, 12, 5)
returns 248 because 5 bits are read from 0000 0000 0000 1111 1000 0000, and these become 1111 1000 (248).
I originally copied the function from a Stackoverflow answer that was written in C. In that version, a result array was passed by reference to the function – however, I need the sum of the result bytes. The function seemed to have several bugs, so I made two improvements:
- If startposition + numBits is still within a single byte, I call another function. This works, but I don't find it very elegant.
- An intermediate result was different in VB.net compared to C, so I added Math.Min(). In C,
tmp |= tmp2 >> (8 - offset);
resulted in 0 in certain cases, but in VB.net it was 1, so I added Math.Min(). (C behaves differently and I had to make a few adjustments).
The problem now is that I discovered a bug yesterday: In the test case, NextBits({48, 2, 250}, 0, 24)
, it should return 300 because all 3 bytes are read (48 + 2 + 250), but the result is 254. This is because the Math.Min() that I added is causing an issue. All previous test cases worked correctly.
Edit October 8: I've just determined that the issue is actually in the line If CUInt(tmp) << CInt(8UI - CUInt(offset)) > 255UI Then
. In the last test case, the code enters the If block 3 times, whereas in the other test cases it goes into the Else
once and then into the If
block twice.
I made a test project:
Option Strict On
Module Module1
Sub Main()
' 1111 1111 1111 1111 1111 1111
'--------------------------------
' 255 255 255
Dim nextBitsResult1 As UInteger = NextBits({255, 255, 255}, 0, 23)
Debug.WriteLine("NextBits 764 = " & nextBitsResult1.ToString())
' 0000 0000 0000 0001 0000 0010
'--------------------------------
' 0 1 2
Dim nextBitsResult2 As UInteger = NextBits({0, 1, 2}, 0, 24)
Debug.WriteLine("NextBits 3 = " & nextBitsResult2.ToString())
' 0000 0000 0000 1111 1100 1000
' ____ _
'--------------------------------
' 0 15 200
Dim nextBitsResult3 As UInteger = NextBits({0, 15, 200}, 12, 5)
Debug.WriteLine("NextBits 248 = " & nextBitsResult3.ToString())
' 0000 0000 0001 1111 0000 0000
' _ ____
'--------------------------------
' 0 31 0
'Dim nextBitsResult4 As UInteger = NextBits({0, 31, 0}, 11, 5)
'Debug.WriteLine("NextBits 31 = " & nextBitsResult4.ToString())
' 0011 0000 0000 0010 1111 1010
'--------------------------------
' 48 2 250
Dim nextBitsResult5 As UInteger = NextBits({48, 2, 250}, 0, 24)
Debug.WriteLine("NextBits 300 = " & nextBitsResult5.ToString())
End Sub
''' <summary>
''' Reads the next <b>n</b> bits from a byte array starting at a specified bit position and sums their values.<br></br>
''' If n bits are to be read across bytes, a new byte is returned, such that the bits of the last byte are considered the leftmost
''' (most significant) bits of the result byte.<br></br>
''' Serves as a look ahead.
''' </summary>
''' <param name="byteArray"></param>
''' <param name="startPosition">The start position (0-based) in bits from which to begin reading.</param>
''' <param name="numBits">The number of bits to read from the byte array.</param>
''' <param name="dest">To specify a position in a temporary output array. This parameter is not relevant for end users.</param>
''' <returns></returns>
Friend Function NextBits(byteArray() As Byte, startPosition As Integer, numBits As Integer, Optional dest As Integer = 0) As UInt32
' https://stackoverflow.com/a/50899946
If IsWithinOneByte(startPosition, numBits) Then
Dim idx As Integer = startPosition \ 8
'Return AnotherFunction(byteArray(idx), startPosition, numBits)
End If
Dim bitmask As Integer = -128
Dim len As Integer = numBits
Dim b As Byte() = New Byte(byteArray.Length - 1) {}
While len > 0
Dim idx As Integer = startPosition \ 8
Dim offset As Integer = startPosition Mod 8
Dim tmp As Byte = byteArray(idx) << offset
Dim next_bits As Integer = offset + len - 8
If len > 8 Then
next_bits += 1
End If
If next_bits < 0 Then
' Don't even need all of the current byte -> remove trailing bits
tmp = CByte(tmp And (bitmask >> (len - 1)))
ElseIf next_bits > 0 Then
' Need to include part of next byte
Dim tmp2 As Byte = CByte(byteArray(idx + 1) And (bitmask >> (next_bits - 1)))
If offset <> 0 Then
tmp = tmp Or (tmp2 >> (8 - offset))
Else
tmp = Math.Min(tmp, tmp2 >> (8 - offset))
End If
End If
' Determine byte index and offset in output byte array
idx = dest \ 8
offset = dest Mod 8
b(idx) = b(idx) Or tmp << (8 - offset)
If CUInt(tmp) << CInt(8UI - CUInt(offset)) > 255UI Then ' In the original C code, this check is redundant because if the value exceeds 255, the assignment b(idx + 1) = 0 effectively handles the overflow. (In C, there are no exceptions)
If idx + 1 < b.Length Then ' The original C code did write an array index too far.
b(idx + 1) = 0
End If
Else
If idx + 1 < b.Length Then
b(idx + 1) = b(idx + 1) Or (tmp << (8 - offset))
End If
End If
' Update start position and length for next pass
If len > 8 Then
len -= 8
dest += 8
startPosition += 8
Else
len -= len
End If
End While
Dim ret As UInt32 = CUInt(b.Sum(Function(x As UInt32) x))
Return ret
End Function
Private Function IsWithinOneByte(startPosition As Integer, numBits As Integer) As Boolean
Dim startByte As Integer = startPosition \ 8
Dim endByte As Integer = (startPosition + numBits - 1) \ 8
Return startByte = endByte
End Function
End Module
Outputs:
NextBits 764 = 764
NextBits 3 = 3
NextBits 248 = 248
NextBits 300 = 254
7 - offset
similarly to the problem in your previous question?