2 byte char -> unsigned short

Started by
2 comments, last by _Josh 22 years, 2 months ago
I''m trying to take the contents of a character array of two bytes and convert it to an unsigned short. The problem is that my formula always comes up 256 short. Can anyone explain why?

unsigned char buff[2];
unsigned short value;

value = (buff[0] << 8) + buff[1];
 
Advertisement
try this:

value = (unsigned short)buff;
-----------------------------------------------------------"People who usualy use the word pedantic usualy are pedantic!"-me
Use a union; it''s the easy way out:
union doublechar {  char buf[2];  short val;}; 

You can then access either val, buf[0] or buf[1].

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!
because you are shifting your upper bits out the register.

unsigned char buff[2];
unsigned short value;
value = (((unsigned short)buff[0]) << 8) + buff[1];

This topic is closed to new replies.

Advertisement