Converting string to bits
Hi,
What is the best way to convert a String with hexadecimal values so that one can split it in uneven chunks of bits (which then will be converted back to Integers)?
Example:
String : "8204CD810C8285"
should somehow be read as:
Bits: 10000010000001001100111010000001000011001000001010000110
The last 20 bits are Month(4), Day(5), Hour(5) and Minute(6)
[397 byte] By [
etoostr] at [2007-11-11 7:45:40]

# 1 Re: Converting string to bits
Ok, I have found one way of doing it. The string is less than 64 bit so I use a Long variable:
Dim tlHeader as String = "8204CD810C8285"
Dim tlHeaderL As Long = Long.Parse(tlHeader, Globalization.NumberStyles.HexNumber)
To read two bits in the middle I mask out the bits I want, and shuffle them to the right (in some cases I also convert to an appropriate type) :
Dim reportRequested As Long = (tlHeaderL And &HC0000000000L) >> 42
I also have to decode longer sequences of hexadecimal-encoded characters.
Example: "41424344" should result in "ABCD".
Suggested code:
Dim sr As New System.IO.StringReader("41424344")
Dim sb As New System.Text.StringBuilder()
Dim buffer(2) As Char
While sr.Read(buffer, 0, 2) = 2 'Read and convert two characters at the time
Dim charVal As Integer = Integer.Parse(New String(buffer), Globalization.NumberStyles.HexNumber)
sb.Append(ChrW(charVal))
End While
If you like it - use it. If not - enlighten me =)