Integers

This cheatsheet looks at integers

Integers represent a whole number stored in binary. Values can be signed (positive or negative) or unsigned (positive only). Integers in computing are fixed-size and therefore are limited in what numbers they can represent. We describe an integer based on the number of bits used to represent it.

Common values of integer are as follows:

Name Size (bits) Range (unsigned)
Byte 8 0 to 255
Short 16 0 to 65535
Integer 32 0 to 4,294,967,295
Long 64 0 to 18,446,744,073,709,551,615
Long Long 128 0 to 282,366,920,938,463,463,374,607,431,768,211,455

Values in italics are not consistant, many places will use integer to mean ‘64 bit’. Some (older) systems even used integers that were 16 bit (win16). Do not assume that types are a certian size without checking the documentation for your language! See types.

Therefore, there is some ambiguity in how big a type is. There are a few ways in which languages have addressed this:

  • In C++, you can use fixed-width integer types which explicitly name the type (eg, uint64_t means 64-bit integer), and leave the types listed above as ‘implementation defined’
  • Java and C# defines type-sizes directly in the standard (rather than have the ambigutiy)
  • Python defines integers has having ‘unlimited precision’, with some implemention spesifics to do with how small(ish) numbers are handled.
  • Javascript uses a single ’number’ type, which may be an integer or a float depending on the value.

Some languages also have support types (eg, big int) for storing large integers beyond what the language usually offers.

Signed Magnitude

Signed bits allow the most signifcant bit to be replaced with a bit representing the ‘sign’ of the value. If the most significant bit is 1 then negative, if its 0 then it’s positive.

  • There are now two ways to represent 0 (1000 0000 = -0 and 0000 0000 = 0)
  • Complications in how the hardware design, ‘signed’ numbers need to be dealt with differently.

Two’s complement

Twos complement notation is commonly used to store signed values. This works by swapping the sign on the most signficant bit, to be the negative of that value.

For example, for 16-bit int, the largest value represents (216-1) when unsigned, however, the value represents (-216-1) when using two’s complement notation. This has the following properties:

  • There is only one representation of 0
  • You can use the same hardware for unsigned and signed numbers
  • You can tell if a number is negative or positive looking at only the MSB

Numerical Bases


Last updated 0001-01-01

Graduation Cap Book Open book GitHub Info chevron-right Sticky Note chevron-left Puzzle Piece Square Lightbulb Video Exclamation Triangle Globe