convert in HEX

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
bellad
Posts: 75
Joined: Tue May 14, 2019 1:47 pm

convert in HEX

Post by bellad » Thu Jun 18, 2020 7:53 am

hello ,
i try convert

Code: Select all

 mem=[1,0,0,1,0,1,0,0,0,0,0,0]
in Hexadecimal
i try with :

Code: Select all

res = ''.join(format(x, '02x') for x in mem)
but :

Code: Select all

NameError: name 'format' isn't defined
thank

User avatar
Roberthh
Posts: 2066
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: convert in HEX

Post by Roberthh » Thu Jun 18, 2020 8:09 am

try:

Code: Select all

res = ''.join("%02x" % x for x in mem)
or

Code: Select all

res = ''.join('{:02x}'.format(x) for x in mem)

bellad
Posts: 75
Joined: Tue May 14, 2019 1:47 pm

Re: convert in HEX

Post by bellad » Thu Jun 18, 2020 8:22 am

ok thank Robert

for the both =

Code: Select all

'010000010001000000000000'

User avatar
jcw
Posts: 36
Joined: Sat Dec 21, 2019 12:08 pm
Location: CET/CEST

Re: convert in HEX

Post by jcw » Sat Jun 20, 2020 12:25 am

Did you mean binary to hex?

Code: Select all

>>> mem=[1,0,0,1,0,1,0,0,0,0,0,0]
>>> ''.join(map(str, mem))
'100101000000'
>>> int(''.join(map(str, mem)),2)
2368
>>> '%x' % int(''.join(map(str, mem)),2)
'940'

Post Reply