Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def take_input(): #loop to take input for the 32 digit binary number
- userInput=None;
- binaryFlag=None; #i mightve made too many bool flags but this was annoying, binaryFlag changes to false if the number isnt binary to stop the loop
- loopFlag=True; #loopflag only exists for the while loop statement, itll almost always be true
- while loopFlag==True:
- binaryFlag=True; #set this to true initially within the loop so every loop it starts true
- userInput=input("Enter a 32 digit binary number: ");
- if len(userInput)==32: #first checks if theres 32 numbers in the string
- print("length ok"); #if there is, prints a simple debug statement "length ok"
- for x in userInput: #same for statement as an earlier project, individually goes through the string to make sure its all 1s and 0s
- if x=="1" or x=="0":
- binaryFlag=True;
- else:
- print(x,"not binary!",sep=" "); #if it isnt all 1s and 0s, break the loop and set binaryFlag to False, to show it isnt binary
- binaryFlag=False;
- break;
- if binaryFlag==True: #if the number given is binary, and 32 digits (we already know because its nested within the length if statement)
- loopFlag=False; #useless statement, just insurance
- return userInput; #then end this function, returning the userinput
- else:
- print("make sure the number is 32 digits");
- def split_string(binaryString): #this function splits the string into 4 8 digit strings
- length=8;
- return [binaryString[i:i+length] for i in range(0, len(binaryString),length)]; #i dont know why this syntax is like this, but this is what the assignment said to do
- def convert_binary(binary): #function to convert binary to decimal
- dec=0;
- for x in str(binary): #if you notice, this is the same exact code we used for the other program we had to convert binary to decimal, just in a function this time
- if x=="1" or x=="0":
- dec=dec*2+int(x)
- else:
- print("make sure your number is binary!")
- break;
- return dec;
- def print_results(binaryList): #function to print the results
- print(convert_binary(binaryList[0]),end=".");
- print(convert_binary(binaryList[1]),end="."); #these have "end="."" because the format the program has to print out is just separated with periods, not entire new lines
- print(convert_binary(binaryList[2]),end=".");
- print(convert_binary(binaryList[3]));
- #this is the actual program, all it does is call the functions we already wrote
- binaryString=take_input();
- binaryList=split_string(binaryString)
- print_results(binaryList);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement