combining ints in C++

Associate
Joined
3 Jun 2007
Posts
23
Hey guys

Just experimenting with C++ for university at the moment and have come across a simple task that I would like to do without finding a solution on the web or text books.

Would like to combine two int's into a single int variable like so:

int a = 244
int b = 201

int c = 244201

Is it even possible?

Thanks for any guidance.
 
Convert into strings and then combine, before converting back into int.

That "combination" is a text approach, not a mathematical operation.
 
multiply a by 1000 giving 244000 and add to b?

if you were using different lengths of int (ie 25 or 24444) you would need to work out how many digits you have and thus the power of ten to use.

Hope this helps
 
Thanks for the extra suggestion dave :)

Edit: Got it all working now :). Aim was to create a RGB number from three separate randomly generated numbers from 0 - 255 to create random colours.
 
Last edited:
Ah, right. The correct way to do that is:

Code:
int rgb = r | g << 8 | b << 16;

C++ has bit-twiddling operators; use them when you want to bit twiddle.
 
Aha, now I understand what you want to do...

technically you should be doing

(r & 255) | ((g & 255) << 8) | ((b & 255) << 16)
 
Back
Top Bottom