Python Forum

Full Version: quick way to convert in both 2 and 3
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
i am collecting simple code to make a variety of conversions in both python 2 and python 3 (e.g. same code works in both versions) Wall

1. integer to hexadecimal:  hex(myint)
2. string to hexadecimal:  ???
3. string to integer:  int(base64.b16encode(codecs.encode(mystr,'ascii')),16)
4. integer to string:  codecs.decode(base64.b16decode(hex(myint).upper().split('L')[0].split('X')[1]),'ascii')
5. hexadecimal to integer:  int(myhex,16)
6. hexadecimal to string:  ???

any suggestions to make #4 simpler Pray   result must be a string (or unicode where that is usable like str), not an array of bytes, and code must work in both python 2 and python 3 Doh  any suggestions for #2 and #6 that would be better than combining other examples Pray
Can you give some examples? Most of this doesn't make sense to me; like string to hexadecimal might have built-in assumptions.
(Oct-31-2016, 06:31 PM)micseydel Wrote: [ -> ]Can you give some examples? Most of this doesn't make sense to me; like string to hexadecimal might have built-in assumptions.

by "string to hexadecimal" i mean:


'micseydel Skaperen' -> '6d696373657964656c20536b61706572656e'

and "hexadecimal to string" is the reverse of that:

'6d696373657964656c20536b61706572656e' -> 'micseydel Skaperen'

something keeps changing my post to have THREE empty lines after my first line of text above.
I suggest you start with
"".join("{:x}".format(ord(char)) for char in string)
and then ask specific questions from there
(Nov-01-2016, 05:30 AM)micseydel Wrote: [ -> ]I suggest you start with
"".join("{:x}".format(ord(char)) for char in string)
and then ask specific questions from there

it works.  is this simpler?

"".join((hex(ord(char)))[2:] for char in string)

s/char/c/ reduces the character count for both
I'm not a fan of using a thing that you then have to slice. That said, "hex" is more explicit than "x". I would keep the full name "char" though.
(Nov-02-2016, 02:47 PM)micseydel Wrote: [ -> ]I'm not a fan of using a thing that you then have to slice. That said, "hex" is more explicit than "x". I would keep the full name "char" though.

i would want to use something other than "char" in things that might be teaching those with C/C++ background.
(Nov-03-2016, 06:03 AM)Skaperen Wrote: [ -> ]i would want to use something other than "char" in things that might be teaching those with C/C++ background.
I don't know what you mean by this.
char is a data type in 'C' - 8 bits signed
I'm familiar with C. I just think it's silly to change your Python because someone else writes C. I believe that when you learn a new language, you should be mindful of your biases from previous ones rather than using them as a baseline.
Pages: 1 2