How to save 16 bit integer value in 8 bit register

General discussion on mikroC PRO for PIC.
Post Reply
Author
Message
dariods
Posts: 25
Joined: 26 Apr 2023 07:12

How to save 16 bit integer value in 8 bit register

#1 Post by dariods » 01 May 2023 18:39

I need to save milliamps which would have the decimal number between 0 to 18000 in the EEPROM of PIC16F877A. The max value that can be saved is 255 in one address of the EEPROM. Search says to do bit shifting. But examples are using hex or binary. So should I convert to hex first. Please explain with code if possible. Thanks.

jumper
Posts: 466
Joined: 07 Mar 2007 14:36

Re: How to save 16 bit integer value in 8 bit register

#2 Post by jumper » 04 May 2023 06:30

Hi,

One 16 bit integer value consist of a HIGHBYTE and a LOWBYTE.

so one way is to use a 8 Bit variable and store each part of the 16 bit integer at 2 different addresses in the EEPROM

for example..

unsigned int REGISTER = 0xABCD;
unsigned char DUMMY=0;

DUMMY=REGISTER; (this will actually put 0xCD in the DUMMY register since that is the LOWBYTE of the REGISTER value)
Write DUMMY to EEPROM address 0
DUMMY=REGISTER>>8; (this will put 0xAB in the DUMMY register)
Write DUMMY to EEPROM adress 1

After you done this the EEPROM should contain 0xCD 0xAB (adr0 adr1)


To fetch the data is somehing similar

Read Data from EEPROM address 1 into REGISTER;
REGISTER=REGISTER<<8; (move the data to the high byte position;
Read Data from EPROM address 0 into DUMMY;
REGISTER=REGISTER+DUMMY;

This method works just as well on binary, decimal or hex numbers as long as they are INT16. All data is binary inside the PIC and HEX, DEC etc is just a representation to make it easier to read for humans.





unsigned int REGISTER = 18000; (which is also in hex 0x4650)
unsigned char DUMMY=0;

DUMMY=REGISTER; (this will actually put 0x50 in the DUMMY register since that is the LOWBYTE of the REGISTER value)
Write DUMMY to EEPROM address 0
DUMMY=REGISTER>>8; (this will put 0x46 in the DUMMY register)
Write DUMMY to EEPROM adress 1

After you done this the EEPROM should contain 0x50 0x46 or DECIMAL 80 DECIMAL 70 (adr0 adr1)


To fetch the data is something similar

Read data from EEPROM address 1 into REGISTER;
REGISTER=REGISTER<<8; (move the data to the high byte position;
Read Data from EPROM address 0 into DUMMY;
REGISTER=REGISTER+DUMMY; (Now register should be 18000 again.)

dariods
Posts: 25
Joined: 26 Apr 2023 07:12

Re: How to save 16 bit integer value in 8 bit register

#3 Post by dariods » 04 May 2023 18:20

Thanks for the solution. I could achieve what I wanted with your help. Thanks again u/jumper

Post Reply

Return to “mikroC PRO for PIC General”