Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typecast to unsigned char and multiply the variables

Tags:

c

printf("%d\n", (unsigned char)255 * (unsigned char)255);

The output of the code above is 65025 but not 1 (255 * 255 (mod 256)). Why?

like image 934
Kevin Dong Avatar asked Jun 08 '15 19:06

Kevin Dong


2 Answers

The multiplication operator * applies the usual arithmetic conversions to its operands. These conversions convert the unsigned char operands to int. See pmg's answer for the standard reference.

Apparently on your system type int is wide enough to hold the result value 65025. On a system with 16-bit int, where INT_MAX == 32767, the multiplication would result in an overflow, causing undefined behavior (typically the high-order bits of the result would be discarded). Most modern systems have 32-bit int.

There is no multiplication operator for integer types narrower than int or unsigned int.

(Strictly speaking, it's possible that the operands could be converted to unsigned int rather than to int. That would happen only if unsigned int can represent the entire range of unsigned char, but int cannot -- and that cannot happen on a system with 8-bit char.)

like image 66
Keith Thompson Avatar answered Oct 20 '22 01:10

Keith Thompson


The operands to * undergo the "usual arithmetic conversions" (C11 Standard p6.3.1.8).

Also see p6.5.5.2: Multiplicative operators

Semantics
The usual arithmetic conversions are performed on the operands.

like image 23
pmg Avatar answered Oct 20 '22 00:10

pmg