Treating a USHORT as two UCHAR's

Started by
3 comments, last by Anon Mike 18 years, 9 months ago
What would be the cleanest way to store two UCHARS inside a 16 bit type instead of using an array? Eg. in pseudo-code: USHORT X; X(UCHAR one) = 12; X(UCHAR two) = 17; print "First uchar equals" + X(UCHAR one); print "Second uchar equals" + X(UCHAR Two); OUTPUT: First UCHAR equals 12 Second uchar equals 17 Thanks in advance for any help you can give me.
Advertisement
uchar uchar1, uchar2;

ushort x = (uchar1) | (ushort)(uchar2 << 8)

uchar1 = x & 0xFF;
uchar2 = x >> 8;

you can also use a macro to collect the bytes instead of hardcoding the AND and bitshift or use the predefined macros in windef.h (or copy the macros to your own files if you're not using windef.h):
HIBYTE
LOBYTE

Of course this is coded in C, but it can be applied to many other non-C languages (for instance, in pascal there's also the logical operators and bitshifts).
Killers don't end up in jailThey end up on a high-score!
assuming you that UCHARs are 8-bits and USHORTs are 16-bits wouldn't you just mask them?

UCHAR1 = 32(decimal) // in binary this will be 0010 0000
UCHAR2 = 64 (decimal) // in binary this will be 0100 0000

USHORT = 65535 (decimal) //in binary this will be 1111 1111 1111 1111

......

edit: just go with the user above [sad]

Beginner in Game Development?  Read here. And read here.

 

Tthanks for the help guys, realy saved my butt here.
#include <windows.h>#include <stdio.h>union foo{    struct    {        UCHAR uc1;        UCHAR uc2;    };    USHORT us;};C_ASSERT(sizeof(foo) == 2);int main(){    foo x;    x.uc1 = 0x11;    x.uc2 = 0x22;    USHORT y = x.us;    printf("%x\n", y);}
-Mike

This topic is closed to new replies.

Advertisement