[SOLVED] Converting unsigned int to two unsigned short and back

Status
Not open for further replies.

jmlabuac

Newbie level 5
Joined
Jan 5, 2012
Messages
8
Helped
1
Reputation
2
Reaction score
1
Trophy points
1,283
Activity points
1,379
Hi... I'm using pic16f877a... I want to save an unsigned int to its eeprom however the value that can only be saved is unsigned short.. I needed to use unsigned int because of its range...

I'm thinking of getting the two bytes of the int and them saving them on two different eeprom memory and when I need to read them I will just get the two bytes and put them back together...

My problem is, I don't have a clue yet as to how I would separate those two bytes ... Can anyone help me? Or is there a much better way?
 

So are you asking how to break the integer to chars and then compose it again?

One way is with union,

union my_value
{
char my_char[2];
unsigned int my_int;
};

The integer and the two chars occupy the same memory area so you can write any of them and read the other, you can write the integer and then read the two chars (my_char[0] my_char[1]) or you can write the two chars and read then as a 16 bit integer.

You can also use shift operation or pointers , there are many alternatives.
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…