How to get the MSB?

A

Andi Hotz

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
 
E

Eric

Andi Hotz said:
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.
 
J

J. Campbell

Andi Hotz said:
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.
 
M

Mike Wahler

Andi Hotz said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top