Home > Enterprise >  How can I read a specific byte in a byte array in VB.NET?
How can I read a specific byte in a byte array in VB.NET?

Time:04-17

I have a binary file being loaded into a Byte array using Dim settingsBinary As Byte() = My.Computer.FileSystem.ReadAllBytes(settingsFile) where settingsFile is the path to my binary file.

Let's say that my binary file has got three bytes and I want to read the first byte as a Boolean (00 = False, 01 = True). How can I get those bytes? I have tried to use this question's answer to read those three bytes, but I can't wrap my head around it.

Just to clarify, I need to get the three bytes separately: Get the first byte, then set CheckBox1.Checked to the first byte, and so on with the other bytes.

CodePudding user response:

A byte array work just like any other array: You can use an indexer to access a specific element.

Dim firstByte As Byte = settingsBinary(0)
Dim secondByte As Byte = settingsBinary(1)
Dim thirdByte As Byte = settingsBinary(2)

And then you can convert the byte into a boolean:

Dim firstBoolean As Boolean
Select Case firstByte
    Case 0
        firstBoolean = False
    Case 1
        firstBoolean = True
    Case Else
        Throw New Exception("Invalid first byte in settings file: " & firstByte)
End Select

(Generalizing the conversion logic into a method that can be used for all three bytes is left as an exercise to the reader.)

  • Related