-
-
Save kaecy/af2c033b79258f0ea2eaa0a0bf3f9213 to your computer and use it in GitHub Desktop.
Binary operations with Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def bitrepresent(dec): | |
base, exp = 2, 7 | |
power = base ** exp | |
str = "" | |
while power != 0: | |
if power <= dec: | |
str += "1" | |
dec -= power | |
else: | |
str += "0" | |
power = power // 2 | |
return str | |
def showBin(dec): | |
byte1 = 0 | |
byte2 = 0 | |
buf = "" | |
if dec > 255: | |
byte2 = dec // 256 | |
byte1 = dec - byte2 * 256 | |
buf = bitrepresent(byte2) + " " + bitrepresent(byte1) | |
else: | |
byte1 = dec | |
buf = bitrepresent(byte2) + " " + bitrepresent(byte1) | |
return buf | |
print(showBin(3)) | |
# -> 00000000 00000011 | |
print(showBin(256*128)) | |
# -> 10000000 00000000 | |
print(showBin(1)) | |
# -> 00000000 00000001 | |
print(showBin(128)) | |
# -> 00000000 10000000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment