[Tutor] string to binary and back... Python 3

Dave Angel d at davea.name
Thu Jul 19 12:46:14 CEST 2012


On 07/19/2012 01:41 AM, wolfrage8765 at gmail.com wrote:
> On Thu, Jul 19, 2012 at 12:16 AM, Dave Angel <d at davea.name> wrote:
>
>> <SNIP>
>> I don't get the same error you did.  I get:
>>
>>  File "jordan.py", line 13
>>     test_int = int(str(test_int) + str(int.from_bytes(os.urandom(1),
>> 'big')))
>>            ^
>>
> test_int = int(str(test_int) + str(int.from_bytes(os.urandom(1), \
>     'big')))
> # That was probably just do to the copy and paste.

That was just the first line that was not indented.  If I thought you
had a one-line while loop, I certainly would have just indented it.  But
I'm sure you have some unknown number of additional lines that were
indented in your original.  Please post in text form.

> <SNIP>
>> I'd also recommend you remove a lot of the irrelevant details there.  if
>> you have a problem with hexlfy and/or unhexlify, then give a simple byte
>> string that doesn't work for you, and somebody can probably identify why
>> not.  And if you want people to run your code, include the imports as well.
>>
>> My problem is not specific to hexlify and unhexlify, my problem is trying
> to convert from string to binary and back. That is why all of the details,
> to show I have tried on my own.
> Sorry that I forgot to include sys and os for imports.

Lots of details that have nothing to do with it.  For example, that
whole thing about adding random digits together.  You could replace the
whole thing with a simple assignment of a value that doesn't work for you.

>
>> As it is, you're apparently looping, comparing the byte memory size of a
>> string (which is typically 4 bytes per character) with the number of
>> significant bits in an unrelated number.
>>
>> I suspect what you want is something resembling (untested):
>>
>>     mybytes = bytes( "%x" % data, "ascii")
>>     newdata = binascii.unexlify(mybytes)
>>
>> I was comparing them but I think I understand how to compare them well,
> now I want to convert them both to binary so that I can XOR them together.
> Thank you for your time and help Dave, now I need to reply to Ramit.

Ah, so you don't actually want binary at all!!!   Why not state the real
problem up front?  You can XOR two integers, without bothering to
convert to a string of ones and zeroes.  Use the carat operator.

print( 40 ^ 12)

I suspect there's an equivalent for strings or byte-strings.  But if
not, it's a simple loop.



-- 

DaveA



More information about the Tutor mailing list