This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

making a short out of a msb+lsb char

Hi all,

I'm new to C and need a hint on an optimization problem.

I have a 16 bit counter, divided into two 8bit SFRs, let's say TH0 and TL0, and I want to transfer them to a short.

I could:
mshort = (short)TH0 * 256 + TL0

but this takes 16bytes, similar to something like:
mshort = (short)TH0 << 8 + TL0

I would like to do it more simple, like:
MSB of mshort = TH0
LSB of mshort = TL0

I tried it that way:
unsigned short *pINT;
pINT = &TH0;

but this is not possible with SFRs.

Something else I tried:
unsigned short mINT;
unsigned char *pChar;
pChar = & mINT;
*pChar = TH0;
*(pChar + 1) = TL0;

results in even more code (31 bytes)

So I think it would be the easiest, if I could place 2 char variables at the same address, covered by my short, like:

unsigned short mINT;
unsigned char mChar[2] (at the same address like mINT)

mChar[0] = TH0;
mchar[1] = TL0;

but I don't know, how to place the mChar array at the same address of mINT. I tried it with:

unsigned char mChar[2] _at_ mINT;

but this is not possible (compiler error).

So anyone here, who could give me a hint how to place both variables at the same address?

Thanks in advance

Marco Della Rocca

Parents
  • Bad idea. Never define your own SFRs. That's what you get ready-made headers from Keil for.

    I totally disagree, as I have found too many buggy ready-made headers from different sources. Therefore I always create my own headers for the target platforms I use.

    However I have to admit that Eric is right. If the derivative is changed and the header is just used as it is, this may cause some bugs that are difficult to catch.

Reply
  • Bad idea. Never define your own SFRs. That's what you get ready-made headers from Keil for.

    I totally disagree, as I have found too many buggy ready-made headers from different sources. Therefore I always create my own headers for the target platforms I use.

    However I have to admit that Eric is right. If the derivative is changed and the header is just used as it is, this may cause some bugs that are difficult to catch.

Children
No data