Break an int into 2 char's

Status
Not open for further replies.

gualala

New Member
Hi,
I'm writing some codes in C18. I have an unsigned int that I wish to break into two chars. I saw something on union struct for a byte, but I don't know how to change it into int. Could anyone help? Thanks.

I wish I can have a variable, say "Value",
Value = 0x8FFF;
Value.HighByte // gives 0x8F
Value.LowByte // gives 0xFF
or any other way that works?

The code I saw for char, so that we can use something like Flags = 0; to set all to zeros or Flags.Timeout = 1; to set a specific value.
Code:
union
{
  struct
  {
    unsigned Timeout:1;
    unsigned None:7;
  } Bit;
  unsigned char Byte;
} Flags;
 
I would do a right-shift and use casts.
Code:
unsigned char low_byte = Value;    // cast
unsigned int tmp = Value>>8;       // right-shift
unsigned char high_byte = tmp;     // cast
 
You can do it eng1's way with shifts or this way with unions:
Code:
union {
	unsigned int Integer;
	struct{
		unsigned char LowByte;
		unsigned char HighByte;
		};
	} Value;

	Value.Integer = 0x1234;
	// Value.HighByte == 0x12;
	// Value.LowByte == 0x34;
The advantage of the union is you can operate directly on the Bytes of the Integer.
 
Or you could do it with a little pointer arithmetic if you like:

Code:
#include <stdio.h>

int main(void)
{
    unsigned int value = 0x8FFF;
    unsigned char *low_byte = (unsigned char *) &value,
        *high_byte = low_byte + 1;

    printf("0x%04x => Low: 0x%02x; High: 0x%02x\n", value, *low_byte, *high_byte);

    return 0;
}

This also allows you access to the individual bytes, but just remember this: https://xkcd.com/371/


Torben
 
Torben said:
Or you could do it with a little pointer arithmetic if you like:

Torben

Are we sure that C18 stores ints in little endian format.

Mike.
 
Pommie said:
Are we sure that C18 stores ints in little endian format.

Mike.

Nope! Just going with what the OP posted, figuring s/he'd just swap the labels if not. Checking the C18 User's Guide confirms it though (page 12).


Torben
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…