philtvr
philtvr

Reputation: 23

How to get the 9th Bit from a short

Im writing a VB.NET app that reads in bytes. I have a short which contains 2 Bytes received from an outside source. I now need to get "Bit 8" from the high byte, i cant work out how to do this i can get "bit 1" back as true to tell me if the source is switched on but cant get "bit 8" which i assume is in the second byte.

i've tried

Dim bit8 = (p_Value And (1 >> 512 - 1)) <> 0

this works for bit 1

Dim bit1 = (p_Value And (1 << 1 - 1)) <> 0

Document of device gives me

low byte

bit 0 through to bit7

High byte

bit 8 *the one i want through to bit 15

I've searched but everything seems to be for single bytes.

Phil

Upvotes: 0

Views: 191

Answers (3)

Chris Dunaway
Chris Dunaway

Reputation: 11216

An alternative is to use the BitArray class. You would then have an array of booleans, one for each bit:

Public Sub Main()
    Dim value As Short = 123
    Dim ba As New BitArray(BitConverter.GetBytes(value))

    'Get 9th bit.  Bit indexing starts at 0
    Dim bit9 = ba(8)
End Sub

Upvotes: 0

dbasnett
dbasnett

Reputation: 11773

If you are working with shorts you can use a left shift

    Dim shrt As Short = 256S ' bit 8 on

    If (shrt And 1 << 8) <> 0 Then
        Stop
    End If

Upvotes: 1

Matt Wilko
Matt Wilko

Reputation: 27342

You should be able to use this function and check the result which will be True if the bit is set (1) or False if the bit is not set (0):

Function IsBitSet(value As Integer, bit As Integer) As Boolean
    Return ((value And CInt(2 ^ bit)) > 0)
End Function

Upvotes: 1

Related Questions