Computer Science - Number

Updated: 2018-12-11

Numerical Types

  • byte: 8 bits, 0xFF
  • short: 2 bytes, 16 bits, 0xFFFF
  • int: 4 bytes, 32 bits, 0xFFFFFFFF
  • long: 8 bytes, 64 bits,

int:

  • 0xffffffff = -1
  • 0x7fffffff = 2147483647
  • 0x80000000 = -2147483648

Java

  • Primitives Types: always have a value, cannot be null, default to false or 0, 0.0f, etc

    • boolean 1
    • byte 8
    • short 16
    • int 32
    • long 64: 1L
    • float 32: 1.0f
    • double 64: 1.0d
  • Reference Types: can be null

Java Byte.toUnsignedInt(): promote byte x to int by adding 1s to the front

public static int toUnsignedInt(byte x) {
    return ((int) x) & 0xff;
}

Tricks

Test Power of 2

Integer k is power of 2 if

(k & (k - 1)) == 0

e.g.

  • k = 256

    • k = 1000000(binary)
    • k - 1 = 0111111
    • k & (k - 1) = 0