Bits Concatenation C++

Hi,
I need help with concatenating several bits values to one big value.
For example:
lets say I have these char variables which I want to concatenate to one value.
unsigned char x = 0x02; //00000010
unsigned char y = 0x01; //00000001
unsigned char z = 0x03; //00000011

and the output should be,e.g. 000000100000000100000011

Can someone please advice on how do I do this.
Last edited on
std::bitset or boost::dynamic_bitset
you can use bit-wise operators http://www.cplusplus.com/doc/tutorial/operators/
( you'll need to promote characters to bigger types )
Bit-wise operators can be hard to debug and read when problem crept up. Thanks for stereoMatching post, now I know there is a std::bitset class I can use directly and this is a God given gift to C/C++ programmers again!!!
This problem is common when dealing with RGB colors as integers. Here is a x86 specific way that is much faster than bitwise operators:
1
2
3
4
5
int color;
char *pcolor=(char*)&color;
pcolor[0]=z;
pcolor[1]=y;
pcolor[2]=x;

And now color has the value you asked for.
And now everyone will murder my guts for teaching pointer casts.
Personally I would have gone for the standard bitshift and bitwise or
@rocketboy9000
1
2
3
4
5
union RGBA{
	//int icolor; //sorry about the Hungarian
	long lcolor;
	char acolor[4];
};
However to work sizeof(int) must be greater or equal than 4.
Edit: Be careful with endianness.

What do you want to accomplish?
What operations do you need to perform that the data should be in that way?
Last edited on
Topic archived. No new replies allowed.