Click here to Skip to main content
15,918,742 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I'm new to C# and I'm having some trouble with bit manipulation.
I have Two bytes. The first thing i want to do is to shift the data in one of the bytes four places normally i would do it like this.

byte1 = 00001111
byte1 = byte1 << 4
byte1 = 11110000

however, this seems to work only for integers?
once i have shifted the data i would like to add them together like this.

byte 1 = 11110000

byte 2 = 00001111

bytes added together = 11111111

What is the best way of doing this?

Thank you.
Posted

The reason it complains it that the bitwise operators are defined for integer and bool only, not byte, so they all get promoted first. Just cast them back, and you'll be fine.
byte b1 = (byte) 0xF0;
byte b2 = 0x0F;
byte b3 = (byte)(b2 << 4);
byte b4 = (byte) (b1 ^ b3);
MessageBox.Show(string.Format("{0}, {1}, {2}, {3}", b1, b2, b3, b4));
^ XORs them together, + adds, | is OR and & is AND.
 
Share this answer
 
byte1 <<= (byte)4;

Works on my machine using VS2008.

Do you get an run-time error, or will it not compile?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900