[Icc-avr] Casting

David Brown david_brown at hotpop.com
Sat Jan 12 15:01:19 PST 2008


John Baraclough wrote:
> Andrew wrote:
>> Hi,
>>
>> When casting and int to two char' (a MSB and LSB) is it safe to do the 
>> following:-
>> Data[7] = (Channel_One >> 8);
>> Data[8] = (Channel_One);
>>
> No

Actually, it *is* safe.  The difference between right shifting a signed 
integer and an unsigned integer is that in the signed case, the MSB is 
treated as the sign bit and repeated (thus 0xff00 is -256, so (0xff00 >> 
1) is 0xff80, or -128), while in the signed case, the MSB of the result 
is 0 (thus 0xff00 is 65280, and (0xff00 >> 1) is 0x7f80, or 32640). 
When you right-shift a signed integer by 8, the low byte is the original 
high byte (including the sign), and the high byte is either 0xff or 
0x00.  In this, since only the low byte of the result is used, the 
effect is the same (and the generated code should be identical).

>> Or am i best doing: -
>>
>> Data[7] = ((unsinged char)Channel_One >> 8);
>> Data[8] = ((unsinged Char)Channel_One);

You want your data charred, but not singed? :-)

>>
> Yes, but you need to adjust your parentheses and spelling.

If you cast Channel_One to an unsigned char before the shift, then the 
shift will reduce the value to 0 (since the cast itself will drop the 
high byte).  Casting the result of (Channel_One >> 8) to unsigned char 
is redundant - assigning it to Data[7] does that anyway (without any 
warnings, which would otherwise have been a good reason for adding the 
cast).  Arguably it would be a little neater to cast Channel_One to an 
unsigned int before the shift, but it is not necessary.

>> or
>>
>> Data[7] = (((unsigned char)(Channel_One & 0xF0)) >> 8 );
>> Data[8] = (Channel_One & 0x0F);
>>
> No, because Data[7] will always be 0 and Data[8] should be cast and will 
> have a maximum value of 15.
>>
>>
>> Andy
>>
>> _______________________________________________
>> Icc-avr mailing list
>> Icc-avr at imagecraft.com
>> http://dragonsgate.net/mailman/listinfo/icc-avr
>>
>>
> HTH
> 
> John
> 
> _______________________________________________
> Icc-avr mailing list
> Icc-avr at imagecraft.com
> http://dragonsgate.net/mailman/listinfo/icc-avr



More information about the Icc-avr mailing list