By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,898 Members | 2,039 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,898 IT Pros & Developers. It's quick & easy.

How to get the MSB?

P: n/a
Hi there

I wonder what might happen if I cast an unsigned (Short or Integer) to char.
The problem I have is I got a value that is at least 2 bytes and I have to
splitt it in chars or byte size portions.

Cheers
Jul 22 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
"Andi Hotz" <an*******@adsl.li> wrote in message news:<3f**********************@news.sunrise.ch>...
Hi there

I wonder what might happen if I cast an unsigned (Short or Integer) to char.
The problem I have is I got a value that is at least 2 bytes and I have to
splitt it in chars or byte size portions.

Cheers


You'd get the LSB if you cast a short or int to char.

Instead, use the right-bit-shift operator (>>) to get the MSB into the
LSB position, then apply a bitwise AND (& 0xFF) to get the LSB.
Jul 22 '05 #2

P: n/a
"Andi Hotz" <an*******@adsl.li> wrote in message news:<3f**********************@news.sunrise.ch>...
Hi there

I wonder what might happen if I cast an unsigned (Short or Integer) to char.
The problem I have is I got a value that is at least 2 bytes and I have to
splitt it in chars or byte size portions.

Cheers


#include<iostream>
using namespace std;

int main(){
short s = 12345;
char lowbits, hibits;
lowbits = s & 255; // Mask with 0000000011111111
hibits = s >> 8;
cout << "In decimal:\n";
for(int i = 0; i<2; ++i){
cout << "Short = " << s << endl
<< "Lowbits = " << (unsigned int)lowbits << endl
<< "Hibits = " <<(unsigned int)hibits << endl << endl;
if(i<1)cout << "In Hexdecimal:\n" << hex;
}
return 0;
}
if you want the bytes from a larger data type, you can make a loop
where you shift 255 left to the byte position, "bit and" it with the
variable, then shift the result back to the low-bit position, and
assign this value to the char.
Jul 22 '05 #3

P: n/a

"Andi Hotz" <an*******@adsl.li> wrote in message
news:3f**********************@news.sunrise.ch...
Hi there

I wonder what might happen if I cast an unsigned (Short or Integer) to char. The problem I have is I got a value that is at least 2 bytes and I have to
splitt it in chars or byte size portions.


unsigned int i = 42;
unsigned char bytes[sizeof i];
memcpy(bytes, &i, sizeof i);

When picking apart the array, don't forget about 'endianness'.

-Mike
Jul 22 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.