Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting signed to unsigned

Tags:

c++

unsigned

is it correct to do this?

typedef unsigned int Index;

enum
{
  InvalidIndex = (Index) -1 
};

I have read that it is unsafe across platforms, but I have seen this in so many "professional" codes...

like image 711
relaxxx Avatar asked May 31 '11 17:05

relaxxx


People also ask

Can you cast signed to unsigned?

To convert a signed integer to an unsigned integer, or to convert an unsigned integer to a signed integer you need only use a cast. For example: int a = 6; unsigned int b; int c; b = (unsigned int)a; c = (int)b; Actually in many cases you can dispense with the cast.

How do I convert signed to unsigned manually?

Mathematically, the conversion from signed to unsigned works as follows: (1) do the integer division of the signed integer by 1 + max , (2) codify the signed integer as the non-negative remainder of the division. Here max is the maximum integer you can write with the available number of bits, 16 in your case.

Why do we need signed and unsigned integer?

Unsigned can hold a larger positive value and no negative value. Unsigned uses the leading bit as a part of the value, while the signed version uses the left-most-bit to identify if the number is positive or negative. Signed integers can hold both positive and negative numbers.


1 Answers

What you read was probably out of Fear, Uncertainty and Doubt. The author of whatever you read probably thought that (unsigned)-1 was underflowing and potentially causing chaos on systems where the bit representation doesn't happen to give you UINT_MAX for your trouble.

However, the author is wrong, because the standard guarantees that unsigned values wrap-around when they reach the edge of their range. No matter what bit representations are involved, (unsigned)-1 is std::numeric_limits<unsigned>::max(). Period.

I'm not sure what the benefit of it is here, though. You're going to get that large, maximum value.. If that is fine, I guess you're good to go.

like image 191
Lightness Races in Orbit Avatar answered Oct 12 '22 04:10

Lightness Races in Orbit