0

I'm trying to convert boolean array to byte.

For example:

Dim boolarray1() As Boolean = {True, True, True, False, False, False, False, False}  

I've been trying to convert this value to another variable called vOUT as byte. In this case vOUT should give me an value 7.

Any help will be appreciated.

1
  • use left shift and or operators. See answer below. Commented Jan 25, 2016 at 10:23

3 Answers 3

2

Using bits with left shift and or operators,

    Dim boolarray1() As Boolean = {True, True, True, False, False, False, False, False}
    Dim vout As Byte = 0
    Dim bytPos As Integer = 0 ' to change order make this 7
    For Each b As Boolean In boolarray1
        If b Then
            vout = vout Or CByte(1 << bytPos)
        End If
        bytPos += 1 ' to change order make this -=
    Next
Sign up to request clarification or add additional context in comments.

1 Comment

Using the Static keyword will cause the code to not work properly if re-used (probably will throw an exception when trying to shift) because the variable will continue holding its value.. you might simply declare it before the loop using Dim
1

Based from your example, if the last element of the array is the MSB or the most significant bit, then you can use this:

    Dim boolarray1() As Boolean = {True, True, True, False, False, False, False, False}
    Dim temp As String = ""
    For i As Integer = 0 To boolarray1.Length - 1
        If boolarray1(i) Then
            temp &= "1"
        Else
            temp &= "0"
        End If
    Next
    temp = StrReverse(temp)
    Dim result As Byte = Convert.ToByte(temp, 2)

result will hold '7' for the given boolarray1. If you need the MSB in the first index, then just remove the line: temp = StrReverse(temp)

4 Comments

That's great to hear. If you have any other concerns, let us know. If not, please click on the answer as 'accepted'. Thanks!
@Nathu - using string is the long way around when you can just use bits. If you insist on strings then traverse the array in reverse in the for and skip the StrReverse.. Strings are expensive to use.
I actually agree with your post @dbasnett. I up voted it. My solution is actually not really a problem if the array is small or there won't be heavy performance restrictions. Cheers!
@Nathu - Agreed if the code is to be executed infrequently.
0

This is how I would do it:

Public Function convertToByte(bits() As BitArray) As Byte
        Dim bytes(0) As Byte
        bits.CopyTo(bytes, 0)

        Return (bytes(0))
End Function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.