Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to convert this RFID Tag number got from this code;
import serial
ser = serial.Serial()
ser.port = "COM1"
ser.baudrate = 9600
ser.timeout = 3
ser.open()
if ser.open is True:
print "Port Not open"
while ser.isOpen():
#ser.timeout = 7
response = ser.read(17)
response = response.encode('hex')
print response
I am getting this 0000000000000000000213780510015dff which is a hexadecimal number, but I want to convert it to decimal or string. When I try to do that, I am getting a token error. How can I fix that?
You say you want to "convert… to string".
You can use unhexlify to do that, or decode('hex').
However, in your case, the only reason you have hex in the first place is that you called encode('hex'), so just… don't do that.
If you want to decode it to an int or a Decimal or something, you can do that by using the appropriate constructor, as Maxime's answer shows. However, rather than converting to hex just to decode as an int, you might want to just decode it directly. Or maybe you want to decode the hex string into a decimal string? Or maybe this is some UUID-style structure, and you want to use struct.unpack to decode it into pieces? Or…? Without knowing exactly what you're trying to do, it's hard to give an exact answer…
You can use int to convert a hexadecimal number into an integer.
>>> int("0000000000000000000213780510015dff", 16)
149595175772052991
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 months ago.
Improve this question
I would like to know how to write in a single line the combination of two hash algorithms in Python. I want to use MD5 and sha256 in one line. Here is my function:
def calcHash(self):
block_string = json.dumps({"nonce":self.nonce, "tstamp":self.tstamp, "output":self.output, "prevhash":self.prevhash}, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
I tried return md5.hashlib(hashlib.sha256(block_string).hexdigest()) but it doesn't work.
Can someone help?
The problem could just be that .hexdigest() produces a string, not a bytes, so you need to encode it again
>>> import hashlib, json
>>> j = json.dumps({"foo":"bar","baz":2022})
>>> hashlib.sha256(j.encode()).hexdigest()
'44ce0f46288befab7f32e9acd68d36b2a9997e801fb129422ddc35610323c627'
>>> hashlib.md5(hashlib.sha256(j.encode()).hexdigest().encode()).hexdigest()
'f7c6be48b7d34bcd278257dd73038f67'
Alternatively, you could directly use .digest() to get bytes from the hash, rather than intermediately converting it to a hex string (though note the output is different)
>>> hashlib.md5(hashlib.sha256(j.encode()).digest()).hexdigest()
'12ac82f5a1c0cb3751619f6d0ae0c2ee'
If you have a great many algorithms in some order, you may find .new() useful to iteratively produce a result from some list of hashes.
BEWARE
md5 is broken from a security perspective and I cannot recommend using it unless it's a required input to a legacy system!
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
For instance:
import socket
s.connect('123.456.78.9', '8080')
word = s.recv(1024)
word.decode()
print(word)
The output will be:
b'this is the string inside the word variable after receiving it from the other end'
is there anyway to get rid of the b at the start, and the quote marks around it?
The b prefix stands for bytes and you are seeing it because the data you receive from the socket is raw bytes. If your message happens to be bytes that are valid text, say ASCII or UTF-8 text, then you will see what looks like the string you expected but with the b prefix. Strings differ from bytes in that some representations of strings require multiple bytes (sometimes a fixed number, sometimes a variable number) per character (technically referred to as a "code point"). In order to convert to between bytes and strings, use:
bytes to str
my_string = b"hello I am a bytes literal".decode()
str to bytes
my_bytes = "hello I am a string literal".encode()
These functions decode and encode also take an optional encoding parameter with the default being 'utf-8', which is what you should use if you do not know what encodings are. If you get an error saying something about a decode error, you may need to specify the encoding.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm doing some experiment with the following code:
import hashlib
password = 16
n = 2 #counter
hash = hashlib.sha256(str(password) + str(n)).hexdigest() #will read the password as string and hash
print hash
What should be the proper code so it can accept a 32byte hex like 000000...0002?
A hex in Python is just a fancy way of writing an integer. So simply set password to your hex value:
password = 0x00000000000000000000000000000002
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi I have a somewhat strange question. I am converting a list of numbers (which represent physical measurements), where each are reported to some specified accuracy in arbitrary units depending on the study it comes from. Here is an example of what I mean:
[...,105.0,20.0,3.5,4.25,9.78,7.2,7.2]
These are of course of type:
<type 'numpy.float64'>.
If I print out the last number, for instance:
print list[-1]
>>> 7.2
However, if accessed in this way, I get:
7.2000000000000002
I understand that floats are by default 64 bits, so doing a calculation with them (i.e. - converting this list of measurements) returns a converted value which is 64 bits. Here is an example of the converted values:
[105.27878958,20.0281600192,3.47317185649,4.27596751688,9.82706595042,7.27448290596,7.26291009446]
Accessing them either way (using print or not), returns a 64 bit number. But clearly there is something else going on, otherwise the print function wouldn't really know how to display the true measurement. I would like to report the converted values to the same level of accuracy as the original measurements. Is there a way I can do this in python?
You have three problems:
1) How do I determine the number of decimal places in the input?
If your Python code literally says [...,105.0,20.0,3.5,4.25,9.78,7.2,7.2], you're out of luck. You've already lost the information you need.
If, instead, you have the list of numbers as some kind of input string, then you have the info you need. You probably already have code like:
for line in input_file:
data = [float(x) for x in line.split(',')]
You need to record the number of places to the right of the decimal before converting to float, for example:
for line in input_file:
places = [len(x.partition('.')[2]) for x in line.split(',')]
data = [float(x) for x in line.split(',')]
2) How do I store that information?
That's up to you. Sorry, I can't help you with that one without seeing your whole program.
3) How do I format the output to round to that number of decimal places?
Use the % operator or {}-style formatting, like so:
print '%.*f' % (places[i], data[i])
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have this long unicode string in python. Of this unicode string I want to read first 1000 bytes.
Use case: I'm trying to send the email body content on a mobile number using the plivo API as a text message. This text message take maximum of 1000 bytes.
So I need to truncate first 1000 bytes from the email body content.
How can this be done ?
If you need the first 1000 bytes then you need to encode the Unicode value first, as the number of bytes varies with the encoding picked.
Then just slice the first 1000 bytes:
encoded = unicodevalue.encode('utf8')
sliced = encoded[:1000]
As it happens, the Plivo Send Message API requires exactly that; 1000 bytes of UTF-8 encoded data. You probably want to truncate the data further to not cut off multi-byte UTF-8 characters:
encoded = unicodevalue.encode('utf8')
sliced = encoded[:1000]
while True:
try:
sliced.decode('utf8')
except UnicodeDecodeError:
sliced = sliced[:-1] # remove one invalid byte
else:
break