Binary Numbers
Representing Binary Numbers
Python supports binary literals by prefixing the number with 0b
or 0B
.
Python
binary_number =
0b1010
# Represents the decimal number 10
Converting Between Decimal and Binary
· Decimal to Binary:
o
Use the bin()
function:
Python
decimal_number =
42
binary_string =
bin(decimal_number)
# Output: '0b101010'
· Binary to Decimal:
o
Use the int()
function with base 2:
Python
binary_string =
'0b1010'
decimal_number =
int(binary_string,
2)
# Output: 10
Bitwise Operations
Python supports bitwise operations on integers, which are often used in low-level programming and data manipulation.
· AND (&): Performs bitwise AND operation.
· OR (|): Performs bitwise OR operation.
· XOR (^): Performs bitwise XOR operation.
· NOT (~): Performs bitwise NOT operation.
· Left shift (<<): Shifts bits to the left.
· Right shift (>>): Shifts bits to the right.
Python
x =
10
# Binary: 1010
y =
5
# Binary: 0101
result_and = x & y
# Output: 0 (Binary: 0000)
result_or = x | y
# Output: 15 (Binary: 1111)
result_xor = x ^ y
# Output: 15 (Binary: 1111)
result_not = ~x
# Output: -11 (Binary: 10101)
Additional Notes
· Binary numbers are treated as integers in Python.
· You can perform arithmetic operations on binary numbers directly.
· Bitwise operations are often used for efficient data manipulation and masking.
Binary Numbers in Python
Representing Binary Numbers
Python supports binary literals by prefixing the number with 0b
or 0B
.
Python
binary_number =
0b1010
# Represents the decimal number 10
Use code with caution.
Converting Between Decimal and Binary
· Decimal to Binary:
o
Use the bin()
function:
Python
decimal_number =
42
binary_string =
bin(decimal_number)
# Output: '0b101010'
Use code with caution.
· Binary to Decimal:
o
Use the int()
function with base 2:
Python
binary_string =
'0b1010'
decimal_number =
int(binary_string,
2)
# Output: 10
Use code with caution.
Bitwise Operations
Python supports bitwise operations on integers, which are often used in low-level programming and data manipulation.
· AND (&): Performs bitwise AND operation.
· OR (|): Performs bitwise OR operation.
· XOR (^): Performs bitwise XOR operation.
· NOT (~): Performs bitwise NOT operation.
· Left shift (<<): Shifts bits to the left.
· Right shift (>>): Shifts bits to the right.
Python
x =
10
# Binary: 1010
y =
5
# Binary: 0101
result_and = x & y
# Output: 0 (Binary: 0000)
result_or = x | y
# Output: 15 (Binary: 1111)
result_xor = x ^ y
# Output: 15 (Binary: 1111)
result_not = ~x
# Output: -11 (Binary: 10101)
Additional Notes
· Binary numbers are treated as integers in Python.
· You can perform arithmetic operations on binary numbers directly.
· Bitwise operations are often used for efficient data manipulation and masking.