Jump to content
  • Advertisement
Sign in to follow this  
Kustaz

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.

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
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).

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!