Question

I have a 16 bit unsigned integer and its values are like this:

byte_val1 = 1000000000000001

From this I need to right shift this and make it like this:

  1100000000000000

I have done this:

 byte_val1 = byte_val1 >> 1

and getting byte_val1 = 100000000000000.

After that I did

  byte_val1 = byte_val1 Or &H80

but I didn't get the desired result... Instead I got 100000010000000.

So what should I do to get that result?

Était-ce utile?

La solution 2

I got it right this time. I did this:

byte_val1 = byte_val1 >> 1

byte_val1 = byte_val1 Or &H8000

And it worked.

Autres conseils

As you are using unsigned data type, the sign bit propagation is not happening. Use a signed integer for the desired results.

What you appear to actually want is to rotate the bits, not shift them:

Module Module1

    Function RORUInt16(n As UInt16, r As Integer) As UInt16
        ' ensure number of places to shift is valid
        r = r And 15
        If r = 0 Then
            ' nothing to do
            Return n
        End If

        ' get bits from RHS
        Dim RHS = Convert.ToUInt16(n And ((2 << r) - 1))
        ' shift the original bits right (loses the RHS saved previously)
        Dim rb = Convert.ToUInt16(n >> r)
        ' put back the lost bits on the LHS
        rb = Convert.ToUInt16(rb Or (RHS << (16 - r)))
        Return rb
    End Function

    Sub Main()

        Dim b1 As UInt16 = Convert.ToUInt16("0000001000000111", 2)

        Console.WriteLine(Convert.ToString(b1, 2).PadLeft(16, "0"c))
        Console.WriteLine(Convert.ToString(RORUInt16(b1, 1), 2).PadLeft(16, "0"c))
        Console.ReadLine()

    End Sub

End Module
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top