shifting order of numbers

Apr 18, 2012 at 10:46am
im still not sure if I should use a string or an int [] (array).
but im trying to get binary string such as 01001011 and perform a left and right shift on them.
left shift results in : 10010110
right shift results in : 00100101

i tried the standard library syntax but it didnt give me wht i needed:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
int main()
{
	int a=10110101;
	int b[1];

	cout<<(2<<2);
	cout<<endl;
	a<<1;

	b[1]=10101010;

	cout<<(b[1]>>1)<<endl;
	
	cout<<a;

	cout<<endl;
}


and I tried a function for it but im not sure if thats the way for it but this is it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void fShifter()
{
	int n =32;
	int a[32];
   //Shifting operation
        if ( Shifter == 1 )//to shift to the left
        {
                for(int i = 1; i < n; i++)
                {
                        a[i-1] = a[i];
                        a[n-1] = '0';
                }
        }
        else if ( Shifter == 2 )//to shift to the right
        {
                for(int i = (n-1); i <= 1; i--)
                {
                        a[i] = a[i-1];
                }
        a[0] = '0';    
        }
}


I had issues with the parameter so i left it empty.


emmmmm help :P i did try my best thts all I got ,, using queues or stack would help but im reading the binary numbers from a file of 79 lines..
I thought that they wouldn't be necessary.
Apr 18, 2012 at 12:09pm
The following doesn't do what you think:

int a=10110101;

In C++, that is a decimal number, meaning it is the same as the number 'ten million, one hundred and ten thousand, one hundred and one'.

Octal and hexadecimal values are commonly used to make working with binary values easy, while keeping it short:

unsigned a = 0xB5;

Now you have a number whose bits are '10110101'. Also note that I changed the type to unsigned. Don't bitshift signed values -- the standard gives you no guarantees when you do.


It might be worth your time to write some functions that convert a string of binary digits to and from a number. For example:

1
2
3
4
5
6
7
8
9
10
unsigned binary_to_integer( const std::string& s )
  {
  unsigned result = 0;
  for (size_t n = 0; n < s.length(); n++)
    {
    result <<= 1;
    result  |= (s[ n ] != '0');
    }
  return result;
  }
 
unsigned a = binary_to_integer( "10110101" );

Hope this helps.
Topic archived. No new replies allowed.