Question about bit shift

  • Thread starter Thread starter Mars Shi
  • Start date Start date
M

Mars Shi

Hi,

I have some special requirements on bit shift by vb.net.

- I want to know how to get the shifted bit value.
- I want to know how to make shifted bit to another variable.

Suppose, I have two variables, byteA is &H0, byteB is &H8F

For the 1st question, if I left shift byteB, like byteB << 1, byteB will
be 00011110 (&H1E), but I want to get the bit being shifted, which is 1,
please tell me how I could get it.

For the 2nd question, I wish the shifted bit from byteB could be shifted
into byteA. The result I want is that, after operation, byteA would be
&H01, and byteB would be &H1E.

Also I wish variables could be byte, integer or long.

Is there any simple operator from VB.net?

Thanks

Mars
 
Hi Mars

Regarding the first question, ALL bites get shifted one position left, but I
assume you mean which bits fall outside.

&H8F = 10001111
10001111 << 1 = 00011110

Well, since bit shifting is actually a 32 bit operation you end up with

00000000 00000000 00000001 00011110

compared to a byte you get the bits shifted by right shifting 8

00000000 00000000 00000001 00011110 >> 8
00000000 00000000 00000000 00000001

In C# you actually get a compiler error if you try to store the shifted
result in a byte.

byte b = 0x8F;
int c = b << 1; // = 0x11E

In VB the compiler will cast the result to the type of b, which means you
will lose the shifted bits. I believe you will need to define b as an
Integer to get the result as an Integer

Dim byteB As Integer = &H8F
Dim byteC = byteB << 1 ' = &H11E

Anyhow, if the bits shifted left falls outside you need to store them before
you shift. You can easily find them by shifting the original value 8 - #
places right in case you shift a byte, 16 - # for short and 32 - # for
integer, and 64 - # for long.

Dim byteShifted = byteB >> (8 - 1)
 
Back
Top