Problem Splitting Integer Variable

hi everyone...

i am facing a problem in my college project...

i have a 16bit unsigned integer variable and i need to store it in the 24C02 EEPROM, but that saves 8bit variable at a time...

the number i need to save is in the form of a decimal integer, how do i split it into 2 unsigned char variables..

i am using the following method

unsigned int val;
unsigned char a,b;

a= (val & 0xFF00)>>8;
b=(val * 0x00FF);


is this code right?

and when i read it back i read it like this

unsigned int val;
val= (((a & 0x00FF)<<8) | (b & 0x00FF));

is this code right?
or is there any other way?

note: i obtain val initially from the user input by using this routine

unsigned int Temp2=0;
Temp2*=10;
Temp2+=Keypress-'0';

Keypress is the input obtained from the keyboard which is ASCII and in the range '0' to '9' and Temp2 is stored in the EEPROM using the Routine i tried


Error:

i tried saving 1234 and when i read it back i got 1024
6666 was read back as 6656
5555 was read back as 5376
1600 was read back as 1536

Parents
  • "the number i need to save is in the form of a decimal integer"

    Not at all. The processor variables don't store any decimal integers. They just store numbers - it's when you present the number that you decide what numeric base to present it with.

    b=(val * 0x00FF);

    You have val (a 16-bit number) and you multiply with 255.

    Take a suitable number - like 12345.
    Convert to binary.
    Perform a multiply by 255 and then try to convert that value to binary.
    Does it seem like it does what you want it to?

    Doing the above is called debugging or validating. Proving if the line does what you hope it should do. You would quickly come to a conclusion - answering your question "is this code right?".

    And you would then also be able to figure out an answer to: "or is there any other way?"

Reply
  • "the number i need to save is in the form of a decimal integer"

    Not at all. The processor variables don't store any decimal integers. They just store numbers - it's when you present the number that you decide what numeric base to present it with.

    b=(val * 0x00FF);

    You have val (a 16-bit number) and you multiply with 255.

    Take a suitable number - like 12345.
    Convert to binary.
    Perform a multiply by 255 and then try to convert that value to binary.
    Does it seem like it does what you want it to?

    Doing the above is called debugging or validating. Proving if the line does what you hope it should do. You would quickly come to a conclusion - answering your question "is this code right?".

    And you would then also be able to figure out an answer to: "or is there any other way?"

Children
More questions in this forum