Hi all Here is some code char prev_ch; unsigned int chksum_read; chksum_read += (WORD)prev_ch*256; chksum_read += (unsigned int)prev_ch<<8; if prev_ch has a value of 0xDB after one of of the two above statments cheksum_read is 0xDA00 instead of 0xDB00. Can anyone explain where I am going wrong?
What is your definition of WORD? As I've said many times before, WORD (and, hence, things like DWORD, etc) is a poor type name because it tells you neither its size nor its signed-ness. It would be far better to choose a name that explicitly shows both. I use: U32 - Unsigned 32 bits S32 - Signed 32 bits U16 - Unsigned 16 bits S16 - Signed 16 bits etc.
I second Andrew's suggestion. I'd add that you should never trust the implicit signed-ness of the bare "char" declaration, since it varies from compiler to compiler. "U8" is also useful as it clearly makes the distinction between a variable intended as a small integer and a variable intended as human-readable text (a "character"). Do you mean that both forms of the statement posted produce the same result? Or that one produces the expected result and one does not? (If so, which one works?) The snippet as shown does not initialize chksum_read, so the += leaves you at the mercy of whatever garbage was in the variable. If that happened to be 0xFF00, you would see the described results. Assuming we're talking about the 8051, if you are going to do a lot of shift by 8s, you might consider a union type.
typedef struct { U8 byte[2]; U16 u16; } BytewiseU16; U8 prev_ch; Bytewise16 chksum_read; // shift left by 8 chksum_read.byte[0] = chksum_read.byte[1]; chksum_read.byte[1] = 0; // add prev_ch shifted left by 8 chksum_read[0] += prev_ch;
"you should never trust the implicit signed-ness of the bare "char" declaration, since it varies from compiler to compiler" and many compilers provide a command-line option to change it!
What is the value of chksum_read before either of the 2 chksum_read += statements? Is it initialized to 0? Jon
prev_ch is a unsigned char not char. word is unsigned int prev_ch is 0 before calculation. this is a strange one?
Could you perhaps show the real code that you have. That would make it a lot easier than talking in circles. Jon