![]() |
![]() |
![]() |
|
|
|||||||
| Micro Controllers Discuss all aspects of micro controllers - building them, coding them, etc. All controllers are welcome - PIC, BASIC, Z8 Encore!, etc. |
|
|
Thread Tools | Display Modes |
|
|
(permalink) |
|
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;
|
|
|
|
|
|
|
(permalink) | |
|
Quote:
Code:
unsigned char low_byte = Value; // cast unsigned int tmp = Value>>8; // right-shift unsigned char high_byte = tmp; // cast |
||
|
|
|
|
|
(permalink) |
|
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 days of the digital watch are numbered. --- |
|
|
|
|
|
|
(permalink) |
|
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;
}
Torben |
|
|
|
|
|
|
(permalink) | |
|
Quote:
Mike. |
||
|
|
|
|
|
(permalink) | |
|
Quote:
Torben |
||
|
|
|
|
|
(permalink) | |
|
Quote:
|
||
|
|
|
| Bookmarks |
| Thread Tools | |
| Display Modes | |
|
|
|
|
||||
| Thread | Thread Starter | Forum | Replies | Latest |
| digital speedometer using AT90S2313 | fever | Micro Controllers | 57 | 29th January 2008 06:44 PM |
| Supermagnets that'll break your arm.. | Analog | Chit-Chat | 11 | 5th February 2007 07:47 PM |
| revew code please | Seb | Micro Controllers | 1 | 22nd February 2005 01:14 PM |
| Break ouy of loop possable? | 1Steveo | Micro Controllers | 2 | 18th February 2004 05:35 PM |
| Can you break an led with too much voltage | daviddoria | General Electronics Chat | 9 | 14th March 2003 06:42 AM |