Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

cutting up variables. 1

Status
Not open for further replies.

MvanH

Technical User
May 15, 2001
19
0
0
NL
Hello people,

I have a big problem,
In my program, I recieve an variable with a value from somewere between 10 and 9999.

The problem is that this unsigned short variable has to be depicted as 4 characters, like 0031 or 0372.
And that's not all.
The big problem is the following.
The first two (HEX) numbers have to go to one unsigned char, and the last two (HEX) numbers have to go to another unsigned char.

for example:
Unsigned short ETU = 0x174;
// the unsigned chars now have to get the following value;

Unsigned char = 0x01;
Unsigned char2 = 0x74;

I tried to solve this by putting the value into a string with string.Format;
But how do i get the number 0x74 into the uchar?
I can get 7 or 4 in by using char = string[3] or string[4]

Then I can get any number between 0 and F into the char, but anything higher then that turns into a character.
Does anybody have an idee how to solve this problem?

Thanks A lot,

Martini.
 
Hi,

The simplest way is to use arithmetics :

unsigned char char1 = (unsigned char) (theShort & 0xFF);
unsigned char char2 = (unsigned char) ((theShot & 0xFF00) >> 8);

Or use an union this way :

union
{
short theShort;
unsigned char theChars[2];
} theUnion;

theUnion.theShort = theShort;
// and just access to theChars[0] for the first two digits, and theChars[1] for the two remaining.

Hope it helps.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top