XXIIVV

Binary numbers are a base 2 numeral system.

A binary number is a number expressed in the base-2 numeral system, which uses only two symbols: 0 and 1. Each digit is referred to as a bit. Because of its straightforward implementation in digital electronic circuitry using logic gates, the binary system is used by almost all modern computers and computer-based devices.

 
—Akane is upset

Basics

Binary to Hexadecimal Conversion

Break down the binary value in chunks of 4, multiply each 1 by its equivalent value, either 8, 4, 2 or 1. Add the resulting numbers together to get the result. For example, the value 1100, or (8*1 + 4*1), is equal to C(decimal 12).

0101Binary
8421Values
41Result: 5

Hexadecimal to Binary Conversion

000004010081000C1100
100015010191001D1101
2001060110A1010E1110
3001170111B1011F1111

Arithmetic

Addition

inputADDoutputcarry
0110
0000
1101
1010

Subtraction

inputSUBoutputborrow
0111
0000
1100
1010

Multiplication

inputMULoutput
010
000
111
100

Bit Masks

AND, or "both", sets individual bits to 0. AND is useful for masking bits, for example, to mask the high order bits of a value AND with $0F: $36 AND $0F = $06.

inputANDoutput
010
000
111
100

ORA(OR), or "either one or both", sets individual bits to 1. OR is useful for setting a particular bit, for example, $80 OR $08 = $88

inputORAoutput
011
000
111
101

EOR(XOR), or "one or the other but not both", inverts individual bits.

inputEORoutput
011
000
110
101

Rotate

ROL rotate one bit left to multiply by 2, and ROR rotates one bit right to divided by 2.

inputopoutput
0110(6)ROL1100(C)
0110(6)ROR0011(3)

Signed Integers

If Bit 7 is not set (as in the first example) the representation of signed and unsigned numbers is the same. However, when Bit 7 is set, the number is always negative. For this reason Bit 7 is sometimes called the sign bit.

BinaryUnsignedSigned
0010 00113535
1010 0011163-93
1111 1111255-1
1000 0000128-128

Add with bitwise in C

int Add(int x, int y) 
{ 
  /* Iterate till there is no carry   */
  while (y != 0) 
  { 
    /* carry now contains common  */
    /* set bits of x and y */
    int carry = x & y;   

    /* Sum of bits of x and y where at  */
    /* least one of the bits is not set */
    x = x ^ y;  

    /* Carry is shifted by one so that adding */
    /* it to x gives the required sum */
    y = carry << 1; 
  } 
  return x; 
} 
— Found a mistake? Submit an edit to binary.htm(137 lines)

incoming(1): assembly