Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between signed and unsigned variables?

I have seen these mentioned in the context of C and C++, but what is the difference between signed and unsigned variables?

like image 890
Sam152 Avatar asked Mar 07 '09 04:03

Sam152


People also ask

What is the difference between signed and unsigned variable types?

The term "unsigned" in computer programming indicates a variable that can hold only positive numbers. The term "signed" in computer code indicates that a variable can hold negative and positive values.

What is the difference between signed and unsigned number?

A numeric variable is signed if it can represent both positive and negative numbers, and unsigned if it can only represent non-negative numbers (zero or positive numbers).

What is the difference between signed and unsigned C++?

C and C++ are unusual amongst languages nowadays in making a distinction between signed and unsigned integers. An int is signed by default, meaning it can represent both positive and negative values. An unsigned is an integer that can never be negative.

How do you know if a variable is signed or unsigned?

A signed variable has to store its sign in some bit. Usually this is the most significant one, but it could be any of them. An unsigned variable has no sign bits; thus, the lowest value it can hold is 0. This means that for an unsigned variable a , the expression a >= 0 will always be true.


1 Answers

Signed variables, such as signed integers will allow you to represent numbers both in the positive and negative ranges.

Unsigned variables, such as unsigned integers, will only allow you to represent numbers in the positive and zero.

Unsigned and signed variables of the same type (such as int and byte) both have the same range (range of 65,536 and 256 numbers, respectively), but unsigned can represent a larger magnitude number than the corresponding signed variable.

For example, an unsigned byte can represent values from 0 to 255, while signed byte can represent -128 to 127.

Wikipedia page on Signed number representations explains the difference in the representation at the bit level, and the Integer (computer science) page provides a table of ranges for each signed/unsigned integer type.

like image 60
coobird Avatar answered Sep 27 '22 18:09

coobird