Separate an 'int' into 2 'char's in C18?

Status
Not open for further replies.

craigwllee

Newbie level 4
Joined
Oct 7, 2007
Messages
6
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Activity points
1,329
c18 byte char int bit

Hi all, I'm working on a project that use Microchip PIC18 series. The only compiler I have is the C18 provided freely from microchip
Anyway it is a simple question. I have an unsigned int that I wish to break it into 2 char that I could send through UART using the putcUSART function. I'm thinking of using the union struct or something, but I can't find references online.
Anyone knows how to do it? Thanks
 

int char mcc18

Can you not use something like the following?

Code:
	int	int_var;
	unsigned char high_char, low_char;
...
	high_char = int_var >> 8;
	low_char = int_var & 0xFF;

Added after 11 minutes:

Or a bit better method for getting the high byte:



Code:
	int	int_var;
	unsigned char high_char, low_char;
...
	high_char = int_var / 256u;
	low_char = int_var & 0xFF;
Cheers,
 

    craigwllee

    Points: 2
    Helpful Answer Positive Rating
c18 int

Code:
typedef union combo {
	int Int;	   
	char Char[2];	   
} Tcombo;

Tcombo x;

x.Int = 0x1234;

x.Char[0] == 0x12; // NOTE! Only if the compiler uses big endian -
x.Char[1] == 0x34; // otherwise it is the other way around.
 

    craigwllee

    Points: 2
    Helpful Answer Positive Rating
microchip c unsigned char int

The Tcombo thing is exactly what I want, I'm thinking the union method is more efficient than taking division and mod? (not sure)
Thank you both for the help =)
 

c18 high byte

Yes, the union method is much more efficient as it only involves moves -
no calculations or loops are necessary.

I've checked the C18 compiler now and it uses litlle endian so the resulting
high byte will be in Char[1]. Like this:

Code:
x.Char[1] == 0x12; // High byte
x.Char[0] == 0x34; // Low byte

See section 2.2 in the manual: https://ww1.microchip.com/downloads/en/DeviceDoc/C18_User_Guide_51288j.pdf

/Ram
 

c18 char

craigwllee said:
The Tcombo thing is exactly what I want, I'm thinking the union method is more efficient than taking division and mod? (not sure)
Thank you both for the help =)
Have a look at this thread to see you question answered:
**broken link removed**

C18 would not actually do the division or shifting. Why don't you try compiling those code snippets to see what is actually done? I do know about the union method, but I prefer the other two methods.

Cheers,
 

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…