Binary To String Conversion - python

I'm relatively new to python and I'm trying to design a program that takes an input of Binary Data and Converts it to a String of Text. I have the following so far but keep getting the following error: TypeError: unsupported operand type(s) for &: 'str' and 'int' Can anyone see where I'm going wrong? And, if so, advise how to fix it?
a = int(input("please enter the binary you want to convert: "))
for str in a:
g = [~(chr(str)&~240)|(e&~240)]
f = 86
e = 231
d = bin(chr(str))
b = (str)
j=(b)
print(j)

There is quite a lot wrong with what you're doing; I'm not sure how you get the error you claim to have, given the other errors in the posted code. In order of reading the function:
Don't call your own variables str, it prevents you from accessing the built-in of the same name. Also, that variable either isn't a str, or causes a TypeError on chr(str).
You can't iterate over an integer for x in y:; this is also a TypeError.
(The error you report) chr(str) returns a string of length one. This is not a valid operand type for &, hence TypeError.
Another operand, e, has not yet been defined, so that will be a NameError.
Irrespective of that, you never use g again anyway.
Or f - what's that even for?
Now e is defined!
bin(chr(str)) will never work - again, chr returns a string, and bin takes a number as an argument.
b = (str) works, but the parentheses are redundant.
Same with j = (b), which is also not indented far enough to be in the loop.
Neither is print(j).
It is not clear what you are trying to achieve, exactly. If you gave example inputs (what format is the "Binary Data"?) and outputs (and what "String of Text" do you want to get?) along with your actual code and the full error traceback this might be easier.
Edit
With the information provided in your comment, it appears that you are trying to reverse these operations:
a = input("please enter the text you want to hide: ")
for ch in a:
## b = (ch) # this still doesn't do anything!
c = ord(ch)
## d = bin(c) # and d is never used
## e = 231 # e is only used to calculate g
f = 86
## g = (((c&240) >> 4)|(e&240)) # which is also never used
h = (((c&15)|(f&240)))
j = bin(h)
print(j)
This produces, for example (a == 'foo'):
0b1010110
0b1011111
0b1011111
However, to convert the input '0b1010110' to an integer, you need to supply int with the appropriate base:
>>> int('0b1010110', 2)
86
and you can't iterate over the integer. I think you want something like:
data = input("please enter the binary you want to convert: ")
for j in data.split():
h = int(j, 2)
...
where the input would be e.g. '0b1010110 0b1011111 0b1011111', or just do one at a time:
h = int(input(...), 2)
Note that, as the function is reversed, you will have to define f before trying to go back through the bitwise operation.

Related

int(), can't convert non-string with explicit base in python

there are two things I can't understand:
1-What does "non-string - with explicit base" means? is it like pointers?
2 How to solve it?
you can check the code and the error it appears on line 25 here. (it is clickable)
Error message:
dec_list.append(int(rmsg[x],2))
TypeError: int() can't convert non-string with explicit base
It's obvious I'm not a python guy but I'm trying to do smth from time to time.
my aaaa.txt file contains
01110001010100010101010001010101011001010110110101010101010101000001010110010101010000010101001001010010110101
local_file=open('aaaa.txt' , 'r', encoding = 'utf-8')
#1st checkpoint open and read the file
a=local_file.read()
n=10
i=0
msg=list() #create a blank list for lsb first
rmsg=list() #create a blank list for msb first
asciimsg=list() #create a blank list for decoded ASCII character
def swap(num):
str_num = str(num)
str_swapped = str_num[-1] +str_num[-2] + str_num[2:-2] + str_num[1] + str_num[0]
return int(str_swapped)
while (n<=len(a)):
# 3th cp: gets the 7 bit, lsb first in the aaaa.txt, one by one till the end
msg.append(a[i+1:n-2])
rmsg.append(swap(a[i+1:n-2]))
n=n+10
i=i+10
print('lsb first binary:')
print(msg)
print('msb first binary(ASCII):')
print(rmsg)
dec_list=list()
for x in range(len(rmsg)):
dec_list.append(int(rmsg[x],2)) #4th checkpoint: convert to decimal
print('ASCII in decimal:')
print(dec_list)
for z in dec_list:
asciimsg.append(chr(z)) #5th cp: use the chr function to convert to ascii
print(asciimsg)
shortmsg=""
for t in asciimsg:
shortmsg=shortmsg+t
print(shortmsg) #6th cp: printing the decoded msg
int is not a str, so convert it to a string first:
dec_list.append(int(str(rmsg[x]), 2))
It is much more Pythonic to use a list comprehension instead of a for-loop like that, though:
dec_list = [int(str(c), 2) for c in rmsg]
int() is a method used in python to convert numbers in the form of strings to integers, for example: "2" is a string, int("2") = 2 so now 2 is an integer, same for your case but the base case is that the initial form of the message is neither an integer nor a string so first you need to convert the message to a string using str(message) and then int(message), also put as int(str(message)).

how to load image cases to measure ROI?

I am trying to apply this code to get the cases I want to measure:
def get_cases(data_dir):
image_folders = os.listdir(data_dir)
image_folders = [f for f in image_f01ders if not f.startswith('.') and '.' not in f]
desired_cases = pd.read_exce1('data/df.xlsm')
desired_cases = desired_cases.query("vetting == 'Y'")
desired_image_ids = desired_cases['ID']
images_to_measure = []
for img in image_folders:
first_ = img.find('.')
if int(img[first_+1]) in desired_image_ids.unique():
images_to_measure.append
images_to_measure = [os.path.join(data_dir, f) for f in images_to_measure]
return images_to_measure
However, when I run this, it throws the following error,
cases = get_cases(data_dir)
File "measure.py", line 70, in get_cases
if int(img[first_+1]) in desired_image_ids.unique():
ValueError: invalid literal for int() with base 10: 'A'
Could someone explain to me why? And how to fix it? Does this have to do with the folder format? or how I find the img files?
the value that img[first_+1] returns is 'A'. it is likely that the number is in base 16. you should pass the number 16 as the 2nd argument to int function. (int(img[first_+1],16)). Doing so will convert the value to an integer from the base 16.
note that if the int function is called without the 2nd argument, it will take the number as a base 10.
if another error comes up, it is possible that something else is wrong.

Error appears when attempting to create a map with folium in Python

My assignment is to create an html file of a map. The data has already been given to us. However, when I try to execute my code, I get two errors:
"TypeError: 'str' object cannot be interpreted as an integer"
and
"KeyError: 'Latitude'"
this is the code that I've written:
import folium
import pandas as pd
cuny = pd.read_csv('datafile.csv')
print (cuny)
mapCUNY = folium.Map(location=[40.768731, -73.964915])
for index,row in cuny.iterrows():
lat = row["Latitude"]
lon = row["Longitude"]
name = row["TIME"]
newMarker = folium.Marker([lat,lon], popup=name)
newMarker.add_to(mapCUNY)
out = input('name: ')
mapCUNY.save(outfile = 'out.html')
When I run it, I get all the data in the python shell and then those two errors mentioned above pop up.
Something must have gone wrong, and I'll admit I'm not at all good with this stuff. Could anyone let me know if they spot error(s) or know what I've done wrong?
Generally, "TypeError: 'str' object cannot be interpreted as an integer" can happen when you try to use a string as an integer.
For example:
num_string = "2"
num = num_string+1 # This fails with type error, because num is a string
num = int(num_string) + 1 # This does not fail because num is cast to int
A key error means that the key you are requesting does not exist. Perhaps there is no latitude key, or its misspelled/incorrect capitalization.

Modulo large prime - TypeError: unsupported operand type(s) for %: 'int' and 'str'

I am trying to partition a large string F to m blocks as follows:
import random
from largeprimes import generateRandom
def generateRandom(length):
t = random.randint(0, 2**length)
str = "{0:b}".format(t)
if (len(str) < length):
str.zfill(length)
return str
def divide_file_block (): #return bi: int
b = []
for i in range (0, m):
b_i = F[(i*blocklen) : ((i+1)* blocklen)]
temp = int(b_i, 2) % q
b.append(temp)
return b
F = generateRandom(102400)
m = 100
blocklen = len(F)/m
q = generateLargePrime(1024) # generateLargePrime is from https://langui.sh/2009/03/07/generating-very-large-primes/
print divide_file_block ()
Note: you shall copy the code from 1 to the current directory, remove the last print statement there and name it largpeprimes.py. This makes the generateLargePrime function importable.
When I test on a small example, it printed out correct result. But when I test on b_i and q having 1024 bits, it printed out the error:
temp = int(b_i, 2) % q
TypeError: unsupported operand type(s) for %: 'int' and 'str'
Could you please explain me why and give me a suggestion to show this problem. Thanks in advance.
The function generateLargePrime sometime returns string
Trying the code I run into the same problem.
Testing it in debugger I got the cause: q has a value of `'Failure after 1100.0 tries.'
This is definitely a string an causes the failures.
I would recommend modifying the generateLargePrime code to throw an exception instead of reporting the failure by returned value.
Few tips for detecting this kind of problems
print out the problematic value
This is the simplest (and probably most popular) quick solution.
something like
b_i = F[(i*blocklen) : ((i+1)* blocklen)]
print "q", q # here is all the magic
temp = int(b_i, 2) % q
would tell you the value
place assert into your code
b_i = F[(i*blocklen) : ((i+1)* blocklen)]
assert isinstance(q, int)
temp = int(b_i, 2) % q
would throw an exception as soon as q is not of type int
run the code in debugger
pdb comes with Python, I prefer ipdb which comes with IPython, both would help you.
have the failing code written as a script
Try to run it via Python interpreter
$ python failingscript.py
as it fails, you simply try once more, but instead of python use pdb or ipdb
$ ipdb failingscript.py
the debugger let you control running the code line by line. Usually I let it run by "c" (continue) command and it soon crashes at the problematic point. Then I use "l" (list) to see, what line of code we are at, and finally use "p" (print) command to print values of variables, which are making problems. This way I used "p q" and found, it is a string.
It takes a moment to learn pdb or ipdb, but it works as turbo resolver so it is definitely the skill to learn. Great tutorial is at PMotW

Python BeautifulSoup string to float

I have downloaded a data set in xml format from online webpage. I have extracted the values tag using beautifulsoup library of python. This gives me unicode values.
graphs = soup.graphs
c = 0
for q in graphs:
name = q['title']
data = {}
for r in graphs.contents[c]:
print float(str(unicode(r.string)))
data[r['xid']] = unicode(r.string)
c = c + 1
result[name] = [data[k] for k in key]
The Source is http://charts.realclearpolitics.com/charts/1171.xml
And I want to make r.string float type
So I did
print float(str(unicode(r.string)))
print float(unicode(r.string))
But I met this err
File "<ipython-input-142-cf14a8845443>", line 73
print float(unicode(r.string)))
^
SyntaxError: invalid syntax
How could i do?
First error is imbalanced round brackets.
print float(str(unicode(r.string))))
^ 4th here
Second error, check the value whether its None or not before making the operation. Otherwise you'll get error ValueError: could not convert string to float: None
So the fix will be:
if(r.string != None):
print float(str(unicode(r.string)))
The syntax error is because of unbalanced parentheses (remove one from right). r.string is probably None, hence the TypeError

Categories