5/14 What's the purpose of "2" in the equation?


#1

I tried using other numbers but it comes out as either error or just flat out wrong. can someone explain what is 2 and the purpose of it? thank you


#2

Can you put here as code what did you try?
I'm not sure if I get what you mean.

print int("1",2)
print int("10",2)
print int("111",2)
print int("0b100",2)

In this code you have function int() which changes first parameter into integer. Second, optional, parameter is system in which first parameter is written.
Let's go:
int("1") - you want change string "1" into integer 1.
int("0b100",2) - you want change string '0b100' into integer. If you would switch it to decimal system (as int("0b100")) it would crack, because there is no number 0b100 in decimal system. But it is in binary system. So you can put 2 as second parameter and this mean "number '0b100' is number in binary system, which base number is 2".

You can check it for another systems (here base is 3).
For exemple print int("1010", 3) will output 30, because: 30 = 27 + 3 = 1 * 3^3 + 0 * 3^2 + 1 * 3^1 + 0 * 3^0

Hope it will help you.


#3

the first parameter in int() has to be a string. If you are given a number, you may first transfer it to a string via str(0b11001010) and then use int('string', 2);

Try:

print int(str(0b11001001), 2)


#4

I believe the 2 is telling the computer that the number (as a string) given is binary as binary numbers work in base 2. 1's and 0's! We work in base ten, so we are telling the computer that we want this number (which is in base 2) in base ten.

print int("1",2) #prints 1
print int("10",2) #print 2 as opposed to 10
print int("111",2) #prints 7 because ((1=4) + (1=2) + (1=1) = 7) as opposed to 110
print int("0b100",2) #prints 4 (is the same as above ^^^)
print int(bin(5),2) #prints 5, honestly can't explain this one well, seems useless as we use bin()
# Print out the decimal equivalent of the binary 11001001.
print int("0b11001001", 2) #prints 201

Hope this helps you out mate! :smiley: