# Treating a USHORT as two UCHAR's

This topic is 4869 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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.

##### Share on other sites
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).

##### Share on other sites
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]

##### Share on other sites
Tthanks for the help guys, realy saved my butt here.

##### Share on other sites
#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);}

1. 1
Rutin
36
2. 2
3. 3
4. 4
5. 5

• 12
• 14
• 9
• 9
• 14
• ### Forum Statistics

• Total Topics
633344
• Total Posts
3011438
• ### Who's Online (See full list)

There are no registered users currently online

×