The Self-Taught Computer Scientist


Download 1.48 Mb.
Pdf ko'rish
bet58/147
Sana17.06.2023
Hajmi1.48 Mb.
#1540634
1   ...   54   55   56   57   58   59   60   61   ...   147
Bog'liq
books-library.net-11301817Az7X6

1
Ones
2
0
Figure 6.3: The powers of 2 used
in the place values in base 2


Introduction to Algorithms
66
After 1, you run out of digits. That means you need to use two digits to represent the number 2, 
just like you have to use two digits in the decimal system to represent the number 10.
In binary, you represent 2 with a 1 and a 0:
10
The 0 stands for no 1s, and the 1 stands for one quantity of 2.
How do you represent the number 3 in binary?
11
The first 1 means one quantity of 1, and the second 1 means one quantity of 2. When you add 2 
and 1, you get 3.
Next up is 4, which in binary is as follows:
100
The first 0 means no ones, the second 0 means no twos, and the 1 means one quantity of four. Add 
them up, and you get 4.
Bitwise Operators
Usually, when you are programming and dealing with numbers, you work with integers and floats 
like 100 and 10.5. There are times, however, when it is useful for you to work with binary numbers 
instead. For example, working with binary numbers can help you quickly solve problems such as 
determining whether a number is a power of 2.
You can use the 
bin
method to work with binary numbers in Python.
print(bin(16))
>> 0b1000
When you print 
bin(16)
, the result is 
0b10000
, which is 16 in binary. As you learned earlier, 
0b
lets you know the number is in binary.
bitwise operator is an operator you can use in an expression with two binary numbers. For 
example, Python’s bitwise AND operator performs Boolean arithmetic bit by bit. When both bits are 
1 (
True
), Python returns 1; otherwise, Python returns 0 (
False
). The logic for each bit in bitwise AND 
is the same as the keyword 
and
in Python. As you know, when you use Python’s keyword 
and
, if both 
sides of the expression are 
True
, Python returns 
True
.
print(1==1 and 2==2)
>> True



Download 1.48 Mb.

Do'stlaringiz bilan baham:
1   ...   54   55   56   57   58   59   60   61   ...   147




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling