Skip to content

Instantly share code, notes, and snippets.

@Fantasim
Last active February 6, 2021 12:30
Show Gist options
  • Save Fantasim/0ab15d62ae61f3a8a73c40d485ff82ec to your computer and use it in GitHub Desktop.
Save Fantasim/0ab15d62ae61f3a8a73c40d485ff82ec to your computer and use it in GitHub Desktop.
Binary, bitwise and bytes.
BASIC BINARY SYSTEM
There are 4 types of int:
- Int8 : 8 bytes | 1 octet. [max: (2^8) / 2 - 1, min: (2^8) / 2 * -1]
- Int16 : 16 bytes | 2 octets. [max: (2^16) / 2 - 1, min: (2^16) / 2 * -1]
- Int32 : 32 bytes | 4 octets [max: (2^32) / 2 - 1, min: (2^32) / 2 * -1]
- Int64 : 64 bytes | 8 octets [max: (2^64) / 2 - 1, min: (2^64) / 2 * -1]
Examples with Int8:
Int8 | binary | Byte array
73 | 01001001 | [ 73 ]
Int8 | binary | Byte array
122 | 01111010 | [ 122 ]
Int8 | binary | Byte array
254 | 11111110 | [ 254 ]
Int8 | binary | Byte array
255 | 11111111 | [ 255 ]
Int8 | binary | Byte array
-1 | 11111111 | [ 255 ]
(255: 256 - 1)
Int8 | binary | Byte array
-50 | 11001110 | [ 206 ]
(206: 256 - 50)
Examples with Int16:
Int16 | binary | Byte array
10000 | 00100111 00010000 | [ 16, 39 ]
Int16 | binary | Byte array
-30000 | 10001010 11010000 | [ 208, 138 ]
(35536: 65536 - 30000)
BITWISE OPERATIONS:
1) AND `&`
-> returns 1 if the corresponding bits of both operands are 1 else it returns 0.
Operand 1 | Operand 2 AND | Operation
0 0 0 & 0 is 0
0 1 0 & 1 is 0
1 0 1 & 0 is 0
1 1 1 & 1 is 1
Example:
var a = 12 //= 01100
var b = 25 //= 11001
a & b = 8 = 01000
2) OR `|`
-> returns 1 if either of the corresponding bits of one operand is 1 else returns 0.
Operand 1 | Operand 2 AND | Operation
0 0 0 | 0 is 0
0 1 0 | 1 is 1
1 0 1 | 0 is 1
1 1 1 | 1 is 1
Example:
var a = 12 //= 01100
var b = 25 //= 11001
a | b = 29 = 11101
3) OR `^`
-> returns 1 if the corresponding bits are different and returns 0 if the corresponding bits are the same.
Operand 1 | Operand 2 AND | Operation
0 0 0 ^ 0 is 0
0 1 0 ^ 1 is 1
1 0 1 ^ 0 is 1
1 1 1 ^ 1 is 0
Example:
var a = 12 //= 01100
var b = 25 //= 11001
a ^ b = 21 = 10101
4) NOT `~`
-> inverts the bit( 0 becomes 1, 1 becomes 0).
Example:
var a = 12 //= 01100
~a = 19 = 10011
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment