binary shift

Hi there
I am going to write a binary code.
I don't know how to use binary shift. my code looks like this :
1
2
3
4
5
6
7
8
9
10
11
12
13


#include<iostream>
using namespace std;
int main(){
    int a,b;
   a=9;      // a is 1001
    b= a <<1;  // b is 10010
    cout<< b;
    return 0;
}


i want my number (here a=9 =1001) after shift become (b=3=0011) not 18=10010.
I think I have to use sth like register or something like that. however i don't how to use that?

thanks
Last edited on
What you're looking for is not bit shifting, but a simple assignment:
b=3;

Or in other words, you should express yourself more clearly.
Maybe you should use a ternary shift instead :-)
He wants a rotate operation.

Unfortunately, C++ doesn't support these natively. You'll have to write your own function to do it.

One way to do it is like this:

1
2
3
4
5
6
7
8
int RotateLeft4Bit(int v)
{
  int ret = (v << 1) & 0x0F;
  if(v & 0x08)
    ret |= 0x01;

  return ret;
}
Last edited on
Even if c++ supported a rotating shift, it would not operate on 4 bits. If you need the actual rol/ror, you can use inline assembly.
Dear Athar
I just wrote a code to learn how it work and use it in my own code which is so big that I think it is boring to bring all of that with explanation.
@hamsterman
I'd like to use it for more than 10 bits and it is difficult to use function. can you explain a little more about rol/ror or inline assembly or put a tutorial.

thanks
hamsterman wrote:
If you need the actual rol/ror, you can use inline assembly.


I don't think rol/ror even work like that. I thought they shift into carry instead of actually rotating.

At least that's how it worked on the old 6502. I don't know how x86 works.

kassik wrote:
it is difficult to use function


What? Why?

Even if you go the inline assembly route, you'd be better off putting the assembly in a separate function.
Dear Athar <...>
What Athar meant was that you don't say what you want clearly. There is a billion ways to turn 9 into 3. I'm amazed that Disch managed to deduce it.

I'd like to use it for more than 10 bits
With ror/rol (or any other instruction) you can't choose any number of bits you want. There are versions for 8, 16, 32 bits. If you want others, you'll have to do (almost) what Disch did. Almost, because that function only shifts one bit and has an unnecessary jump.
As for using inline asm, it depends on your compiler.

I don't think rol/ror even work like that
I think they do. Storing the bit in CF is what regular shifts do. At least so says my asm instruction reference - http://flatassembler.net/docs.php?article=manual#2.1.5
Last edited on
Topic archived. No new replies allowed.