954,479 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Using binary operators!

Hello ladies and gents,

I'm starting on the next exercise, but I'm puzzled a bit and was wondering if any of you might help me with this.

I have to enter four integer numbers, non negative and smaller then 16 into ONE variable int x, now, the thing I was wondering is, do I have to use an array for this int x, so that I get int x[3] put the four numbers smaller then 16 into the array or is it possible to solve this solely by using a certain bit operator?

The idea is, when those four numbers are entered, I then have to select a number from 0 to 3 and depending on the selection it has to give me the previous entered number smaller then 16!

Hope you understood what I'm trying to accomplish.

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

Play around with this and see what you can come up with:

#include <iostream>

using namespace std;

#define bit(x) (1UL << (x))

int main()
{
  unsigned int x = 0;

  x = 1; // 00000001
  cout<< x <<endl;
  x |= bit(1) | 1; // 00000011
  cout<< x <<endl;
  x |= bit(2) | 1; // 00000111
  cout<< x <<endl;

  // Get back a sliver
  cout<< (x >> 1) <<endl; // 00000011
  cout<< (x >> 2 << 2) <<endl; 00000100
}
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

I will ;)

Thanks Narue!

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

Hi Narue,

Ive been playing around with the code you gave me and alltough I'm pretty sure I understand what is happening, I can't really figure out how this is going to help me in getting four different numbers smaller then 16 into one variable x :o

I understand that when having four bits 1111, I get a decimal maximum of 15.

I understand that by using those binary operators << or >> you can shift the binary to the left or right adding a ZERO to the four bits and changing the decimal number.

I understand that using the code x = bit(i) | 1; am putting the bit (i) to 1 and changing the decimal number again.

Have a few question about it also

#define bit(x) (1UL << (x))

int main()
{
  unsigned int x=0;

  x |= bit(0) | 1; // 00000001 = 1
  cout<< x <<endl;
  x |= bit(1) | 1; // 00000011 = 3
  cout<< x <<endl;
  cout<< (x >> 1 << 1) <<endl; // 00000010 = 2 
  x |= bit(2) | 1; // 00000111 = 7
  cout<< x <<endl;
  x |= bit(6) | 1; // 01000111 = 71
  cout<< x <<endl;

  // Get back a sliver
  cout<< (x >> 1) <<endl; // 00100011 = 35
  cout<< (x >> 2 << 2) <<endl; // 01000100 = 68
  cout<< (x >> 1) <<endl; // 00100011 = 35
  cout<< (x >> 1 << 1) <<endl; // 01000110 = 70
  cout<< (x >> 2 << 1) <<endl; // 00100010 = 34

  return 0;
}


1) #define bit(x) (1UL << (x)): what does the UL stand for and what does it do? Unsigned Long?

Also, when I deleted UL and left (1 << (x)) it worked aswell, with this the binary operator makes it shift one place to the left.

2) Tough I understand what happens when using these binary operators, I can't really figure out how this is going to help me getting those four decimal numbers into a variable x :?:
Not only that, but when they are entered, I have to retrieve one of them using a number from 0 to 3, so, when I have decimal numbers entered like:
3
7
14
6

And I enter for example 1, it should give me 7 as result, sorry, but I don't see how this could be done with the example code you gave me :o

If you could give me any further hints, I would greatly appreciate it.

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

Each nibble takes up 4 bits. So shifting by 4 times the desired position would get you to the desired spot.

#include <stdio.h>

unsigned int set(unsigned char nibble, int pos)
{
   return nibble << ( pos * 4 );
}

unsigned char get(unsigned int value, int pos)
{
   return ( value >> ( pos * 4 ) ) & 0xF;
}

int main ( void )
{
   unsigned int x = set(3,0) + set(7,1) + set(14,2) + set(6,3);
   int i;
   for ( i = 0; i < 4; ++i )
   {
      printf ( "get(%d) = %d\n", i, get(x,i) );
   }
   printf ( "x = %X\n", x );
   return 0;
}

/* my output
get(0) = 3
get(1) = 7
get(2) = 14
get(3) = 6
x = 6E73
*/
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

Thanks for the help Dave, but, can you explain this to me without using those two functions, it's an exercise in wich functions an references aren't seen yet and to be honest, I'd rather do this exercise without them, it's to confusing for me at this moment ;)

So, how could I do that without using those functions?

Thanks

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

Thanks for the help Dave, but, can you explain this to me without using those two functions, it's an exercise in wich functions an references aren't seen yet and to be honest, I'd rather do this exercise without them, it's to confusing for me at this moment ;)

So, how could I do that without using those functions?

I feel like I'm stepping on Narue's toes already, but...

#include <stdio.h>

int main ( void )
{
   unsigned int   x;
   unsigned char  nibble;
   /*
    * Set the value 3 in the 0th nibble.
    */
   x = 3 << (0 * 4);
   printf ( "x = %04X\n", x );
   /*
    * Add in the value 7 in the 1st nibble.
    */
   x += 7 << (1 * 4);
   printf ( "x = %04X\n", x );
   /*
    * Add in the value 14 in the 2nd nibble.
    */
   x += 14 << (2 * 4);
   printf ( "x = %04X\n", x );
   /*
    * Add in the value 6 in the 3rd nibble.
    */
   x += 6 << (3 * 4);
   printf ( "x = %04X\n", x );
   /*
    * Get the value in the 1st nibble.
    */
   nibble = ( x >> (1 * 4) ) & 0xF;
   printf ( "nibble = %d\n", nibble );
   return 0;
}

/* my output
x = 0003
x = 0073
x = 0E73
x = 6E73
nibble = 7
*/


The amount of left or right shift is some parenthesized multiple of 4, which is enough bits for each nibble value.

The bits could be ORed in (|) instead of adding.

For extraction, the & 0xF masks off the lowest 4 bits, after the appropriate shift, and clears any others.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

Thanks,

But why does the nibble need to be a char and can't it be an integer?

Can you explain how this can be summorized: printf ( "x = %04X\n", x );

Using cout, can I write it like this: cout<< "x = " <

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

>But why does the nibble need to be a char and can't it be an integer?

It doesn't need to be a char. [rhetorical]But why waste a full int for 4 bits?[/rhetorical]

>Can you explain how this can be summorized: printf ( "x = %04X\n", x );
>Using cout, can I write it like this: cout<< "x = " <Can I compare putting the numbers 3, 7, 14, 6 into a binary operator as a sort of array?

I suppose you could think of the int as an array of nibbles.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

Nope, can't figure it out :sad:

int main()
{
	unsigned int x, j;
	unsigned char  nibble;
	
	for (int i=0;i<4;i++)
	{
		cin>>j;cin.get();
		x+= j << (i * 4);
	}

	for (i=0;i<4;i++)
		cout<< hex << nibble = x << (i * 4) <<endl;

	return 0;

}


What I want to do is, is enter four different numbers smaller then 16 and then just print them!

One error that I keep getting is: error C2297: '<<' : illegal, right operand has type 'class ostream &(__cdecl *)(class ostream &)'

This has to do with the last loop, but don't know how to solve it, could someone please help me.

Thank you!

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 
cout<< hex << nibble = x << (i * 4) <<endl;


Try not do so much as a one-liner: it can add to confusion and and be more error prone. Also,cout adds some fun that printf didnt when it comes to displaying the value.

unsigned int x, j;
	unsigned char  nibble;
	
	for (int i=0;i<4;i++)
	{
		cin>>j;cin.get();
		x+= j << (i * 4);
	}


You don't initializex before you add to it -- not good. Initialize it to 0.

unsigned int x, j;
	unsigned char  nibble;
	
	for (int i=0;i<4;i++)
	{
		cin>>j;cin.get();
		x+= j << (i * 4);
	}

	for (i=0;i<4;i++)


This is a MSVC6 thing, but it is incorrect:i should not be in scope for the the second for loop.

From the top:

#include <iostream>
using namespace std;

int main()
{
   unsigned int x = 0, i, j, nibble;

   for ( i = 0; i < 4; ++i )
   {
      cin >> j;
      cin.get();
      x += j << (i * 4);
   }

   for ( i = 0; i < 4; ++i )
   {
      nibble  = x >> (i * 4);
      <strong>nibble &= 0xF;</strong>
      cout << hex << nibble <<endl;
   }

   return 0;
}
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

Pfffffffffff, why do you guys and girls allways make it look so simple :mrgreen:

On a serious note, thanks a lot Dave ;)

>>Try not do so much as a one-liner: it can add to confusion and and be more error prone. Also, cout adds some fun that printf didnt when it comes to displaying the value.

Do you mean that It's best not to write to much code on one line? Maybe a stupid question, but being a non native English speaking person, I'dd like to be sure!

>>

nibble &= 0xF;


Could you explain this please, I think I understand 0xF wich equals a number in the decimal notation correct?

But why do you use the ampersand '&' , what does it do, I don't understand what happens with the nibble when you use it?
Is there a possibility to write a piece of code without using '&'?

Is the use of '&' related to the error message I got?

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 
Do you mean that It's best not to write to much code on one line?

Yes.
nibble &= 0xF;
Could you explain this please, I think I understand 0xF wich equals a number in the decimal notation correct?It isolates the lowest 4 bits (values between 0 and 15).But why do you use the ampersand '&' , what does it do, I don't understand what happens with the nibble when you use it?
Is there a possibility to write a piece of code without using '&'?No. Watch what it does:

#include <iostream>
using namespace std;

int main()
{
   unsigned int x = 0, i, j, nibble;

   for ( i = 0; i < 4; ++i )
   {
      cin>>j;
      cin.get();
      x+= j << (i * 4);
   }

   cout << hex << x << endl;

   for ( i = 0; i < 4; ++i )
   {
      nibble  = x >> (i * 4);
      cout << "before: " << hex << nibble << endl;
      nibble &= 0xF;
      cout << "after:  " << hex << nibble << endl;
   }

   return 0;
}

/* my output
15 1 9 3
391f
before: 391f
after:  f
before: 391
after:  1
before: 39
after:  9
before: 3
after:  3
*/
Is the use of '&' related to the error message I got?

No. It's because of trying to do too much in one line.

cout<< hex << (nibble = x << (i * 4)) <<endl;
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

Ok, got it now, thanks for the explanation :)

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

I think JoBe got it, folks are smart in Belgium!
Just in case there are some stragglers, here is another twist to Dave's wonderful code. I am trying to make the whole thing more visible ...
[php]
// bitwise operations << shift left, >> shift right, & bitwise AND
// a nibble is 4 bits, char is 8 bits, int is 32 bits
// try to store values 3, 7, 14, 6 in an integer

#include

// prototype
void dec2bin(long decimal, char *binary);

int main ()
{
unsigned int x;
unsigned char nibble;
char binary[80];

x = 0;
printf("count groups of 4 bits (nibbles) from right to left ...\n\n");

// put 3 into the first group of 4 bits (nibble #0)
x = 3 << (0 * 4);
dec2bin(x,binary);
// added 00 to make the groups of 4 bits show better
printf("value 3 in nibble #0 = 00%s\n", binary);

// put 7 into the second group of 4 bits (nibble #1)
x += 7 << (1 * 4);
dec2bin(x,binary);
printf("value 7 in nibble #1 = 0%s\n", binary);

// put 14 into the third group of 4 bits (nibble #2)
x += 14 << (2 * 4);
dec2bin(x,binary);
printf("value 14 in nibble #2 = %s\n", binary);

// put 6 into the fourth group of 4 bits (nibble #3 and so on, plenty of space)
x += 6 << (3 * 4);
dec2bin(x,binary);
printf("value 6 in nibble #3 = %s\n", binary);

printf("\n... retrieve values ...\n\n");

// retrieve the values in nibble #0, #1, #2 and #3
// & is bitwise AND, 0xF is binary 1111
nibble = ( x >> (0 * 4) ) & 0xF;
printf ( "value in nibble #0 = %d\n", nibble );
nibble = ( x >> (1 * 4) ) & 0xF;
printf ( "value in nibble #1 = %d\n", nibble );
nibble = ( x >> (2 * 4) ) & 0xF;
printf ( "value in nibble #2 = %d\n", nibble );
nibble = ( x >> (3 * 4) ) & 0xF;
printf ( "value in nibble #3 = %d\n", nibble );

getchar(); // wait
return 0;
}

//
// accepts a decimal integer and returns a binary coded string
//
void dec2bin(long decimal, char *binary)
{
int k = 0, n = 0;
int neg_flag = 0;
int remain;
char temp[80];

do
{
remain = decimal % 2;
decimal = decimal / 2; // whittle down decimal
temp[k++] = remain + 0x30; // makes characters 0 or 1
} while (decimal > 0);

while (k >= 0)
binary[n++] = temp[--k]; // reverse spelling
binary[n-1] = 0; // end with NULL = EOS
}
[/php]

vegaseat
DaniWeb's Hypocrite
Moderator
5,986 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 
I think JoBe got it, folks are smart in Belgium!

Smart people here, of course, but don't think I'm one of them, certainly not in programming :cheesy:

But, must admit, it is fun to try and be smart :cheesy:

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 

Seeing as the next exercise is also about the use of binary operators I figured I'd use the same tread.

Idea is to multiply a certain number (not to large) by one hundred using the binary operator << a few times :!:

My solution:

int main()
{
	unsigned short x;

             cin>>x;cin.get();

             cout<< ((x << 7) - (x << 5) + (x << 2))<<endl;

	return 0;


Alltough this works, I was wondering If it isn't possible to get this done without adding and subtracting this and still only use one variable x?

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 
(x << 7) - (x << 5) + (x << 2)


What this is doing is this:

(x * 128) - (x * 32) + (x * 4)


Which would be the same as

x * (128 - 32 + 4) // which is the same as...
x * 100


So you could do it other ways too, like this

(x << 6) + (x << 5) + (x << 2) // (64 + 32 + 4)


But unless you are multiplying be a power of 2, you'll probably need to add and/or subtract to achieve the desired result.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

Hi Dave,

I allready understood this threw the exercise before this one and your explanation on that one, thanks ;)

Maybe I didn't explain it to well, so here it goes.

Using the binary operator <<, I can make sure that a certain variable is multiplied, this however is done in my example and your examples by using the + and - operator!

Question is, could this same exercise be done without the use of these two operators but still with the use of the binary operator << ?????

JoBe
Posting Pro in Training
420 posts since Sep 2004
Reputation Points: 51
Solved Threads: 4
 
Question is, could this same exercise be done without the use of these two operators but still with the use of the binary operator << ?????

Unless someone wants to show me a new trick...But unless you are multiplying be a power of 2, you'll probably need to add and/or subtract to achieve the desired result.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You