-1

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arindam Das
  • 699
  • 4
  • 20
  • 39

3 Answers3

0

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Travis G
  • 1,592
  • 1
  • 13
  • 18
0

I got it right this time. I did this:

byte_val1 = byte_val1 >> 1

byte_val1 = byte_val1 Or &H8000

And it worked.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arindam Das
  • 699
  • 4
  • 20
  • 39
  • This would always append 1 to the left. What if your right-most bit is 0? You may want to use mask instead of `&H8000`, which is initially equal to `byte_val1 And &H8000`. Then do `byte_val1 = byte_val1 Or mask`. – Victor Zakharov Jul 27 '13 at 19:27
0

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
Andrew Morton
  • 24,203
  • 9
  • 60
  • 84