Posts: 4,646
Threads: 1,493
Joined: Sep 2016
Oct-31-2016, 06:59 AM
(This post was last modified: Oct-31-2016, 06:59 AM by Skaperen.)
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)
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

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

any suggestions for #2 and #6 that would be better than combining other examples
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Posts: 4,646
Threads: 1,493
Joined: Sep 2016
Nov-01-2016, 04:40 AM
(This post was last modified: Nov-01-2016, 04:43 AM by Skaperen.)
(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.
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Posts: 4,646
Threads: 1,493
Joined: Sep 2016
Nov-01-2016, 07:05 AM
(This post was last modified: Nov-01-2016, 07:06 AM by Skaperen.)
(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
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Posts: 4,646
Threads: 1,493
Joined: Sep 2016
(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.
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.