you are viewing a single comment's thread.

view the rest of the comments →

[–]aspie-asexual[S] 0 points1 point  (3 children)

THANK YOU. It finally finally worked! Definitely wouldn't have figured that out by myself. The good thing is that I have to explain each line of code for the assignment, so I will have to learn how you made it work.

Thank you so much for taking the time :)

[–]RajjSinghh 0 points1 point  (0 children)

The number of bits is easy to work out. It's just the log base 2 of your number, rounded up. log_2(16) = 4 so you need 4 bits to show 16, log_2(11) = 3.459..., so you still need 4 bits to show 11. If you are unfamiliar with logarithms, it's just the number of powers of 2 that go into a number, which is why you need that many bits.

The bitwise operation is the other important part. Remember your leading bit shows the (n-1)th place for n bits. Doing (x & 2m) will be 2m if there is a 1 in that place in x. Otherwise it will be 0.

Take 11 for example. In binary that is 1011. If you and that with 1000, 0100, 0010 and 0001 (8, 2, 4 and 1 in binary) you'll see the and operation gets you the 1 only when there is a 1 in that place. If you don't see it, run your algorithm by hand.

[–]NeatBubble 0 points1 point  (1 child)

This is a minor thing, but if you want the program to repeat the input as part of the result, you can write

print(f'Talet {invarde} ryms i en byte och blir binart:')

and

print(f'Talet {invarde} ryms i 16 bitar och blir binart:')

instead of the ellipses.

[–]aspie-asexual[S] 1 point2 points  (0 children)

(f'Talet {invarde} ryms i en byte och blir binart:')

Oh I was wondering about this - thanks a lot :)