Posts

Showing posts with the label signed int

C++: From byte to signed int

Spanish version / Versión en Español If we cast a byte, that is, an unsigned char, to and int, we'll get a value between 0 and 255, since int, even thpugh it's signed, contains that range of values. If our intention is to see that byte as a value between -128 and 127, we must cast to signed char before casting to int. So watch it. unsigned char b = 248; int i = static_cast<int>(b); //248 int j = static_cast<int>( static_cast<char>(b) ); //-8 I prefer using static_cast to the traditional, equivalent casting style because it makes casts easier to find when you suspect there is a problem caused by them. (it's easier to find "static_cast<int>" than "(int)" )

C++: De byte a signed int

Versión en inglés / English version Si casteamos un byte, o sea un unsigned char, a int, obtendremos un valor entre 0 y 255, ya que int, pese a ser signed, contiene ese rango de valores. Si nuestra intención es ver ese byte como un entero entre -128 y 127, lo que debemos hacer es primero castear a signed char. Y recién después de hacer eso, castear a int. unsigned char b = 248; int i = static_cast<int>(b); //248 int j = static_cast<int>( static_cast<char>(b) ); //-8 Prefiero usar static_cast antes que la forma tradicional (y equivalente) de castear, porque facilita encontrar los casteos cuando uno sospecha que generan problemas (es más fácil encontrar "static_cast<int>" que "(int)" ).