Sign in to follow this  

Treating a USHORT as two UCHAR's

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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);
}

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this