Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conversion between signed and unsigned in C++

Tags:

c++

casting

Consider the following C++ code:

#include <cstdio>

using namespace std;

int main()
{
    int ia = -5;
    unsigned int uia = ia;
    char ca = -5;
    unsigned char uca = ca;

    printf("%d\n", (ia == uia));
    printf("%d\n", (ca == uca));

    return 0;
}

The output is

1
0

I don't understand what's the difference between int and char while casting from signed to unsigned?

Could you please enlighten me?

like image 700
imsrch Avatar asked Apr 14 '13 03:04

imsrch


People also ask

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.

What is the difference between signed and unsigned in C?

A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295]. The signed integer is represented in twos complement notation.

What is the difference between a signed and an unsigned number?

Signed numbers use sign flag or can be distinguish between negative values and positive values. Whereas unsigned numbers stored only positive numbers but not negative numbers.

How do I convert an int to unsigned?

1) Add UINT_MAX + 1 to your signed number and store it in an unsigned variable. (this will convert the signed integer to an unsigned integer of same magnitude). 2) Unsigned number of same binary representation can be found by multiplying each digit in the binary representation by its place value and adding them up.


1 Answers

They both behave the same when converting from signed to unsigned. What behaves differently is the == comparison. It behaves as expected for the int/unsigned, but when you compare two smaller types, they both get promoted to int first. So what happens is that the unsigned 8-bit representation of -5 and -5 both get promoted to int and then get compared. These are obviously different and fail the comparison.

like image 156
Mark B Avatar answered Oct 14 '22 06:10

Mark B