> bdrmachine wrote: > > Can someone give me a C example of how to combine 2 unsigned > > chars (msb and lsb) and store as a unsigned int (L)?
L = (((unsigned) msb) << 8) | lsb; The outermost parentheses are redundant, but they highlight the intent. > > It seams the technique I'm using is more involved then it > > should be. Would "L= msb<<8 + lsb;" work? No. The precedence of + is higher than <<, so your expression is the same as... L = msb << (8 + lsb); A naive change... L = (msb << 8) + lsb; ...still as problems in that msb may promote to signed int, and left shifting a signed int can potentially result in undefined behaviour. > > I'm working on a program for a 8 bit microcontroller. That is incidental. I'd try to write C code that works on _any_ architecture. > > Unsigned char's are 8 bits long and unsigned int's are > > 16 bits. Throw in the words 'at least' and you've described every C implementation. Your 'constraints' are better viewed as minimum requirements. Requirements you are guaranteed to have on any C implementation. Thomas Hruska <[EMAIL PROTECTED]> wrote: > > Using concepts from Safe C++ Design Principles, do: > > L = (UInt16)((((UInt16)msb) << 8) | (UInt16)lsb); I've gotta tell you Thomas, glancing at that design, 'safe' isn't the first word that comes to mind. At the very least, a book on safe design in C++ should not be using deprecated C style casts. I can't see how the following is any less safe than your version... L = (Uint16(msb) << 8) | lsb; -- Peter
