1

While using MicroPython, I recently copied my "toBits()" function from python. My code is this:

def tobits(s):
    bits = ""
    for c in s:
        bits2 = ''.join(format(ord(i), '08b') for i in c)
        bits = bits + bits2
   return bits

However, When using this function, I got the error: "NameError: name 'format' isn't defined"

I'm assuming MicroPython doesn't have "format" in it. Is there a different way to convert a string to bits in MicroPython?

2 Answers2

3

Just figured this out, I ended up replacing the bits2 line with:

bits2 = ''.join('{:08b}'.format(ord(i)) for i in c)
buddemat
  • 4,552
  • 14
  • 29
  • 49
  • So the `format` member function for strings exists but the free standing function doesn't? That makes no sense. – Mark Ransom Jul 18 '22 at 16:37
  • I agree, I found someone with a similar problem here: https://forum.micropython.org/viewtopic.php?f=2&t=8561 Not sure why the free standing function isn't in micropython – gradStudent Jul 18 '22 at 17:49
0

I know this works in regular Python, not sure about MicroPython.

bits = ''.join(bin(i)[2:].rjust(8,'0') for i in c)
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • I tried "bits2 = ''.join(bin(i)[2:].rjust(8,'0') for i in map(int, c))" in MicroPython, and got the error "AttributeError: 'str' object has no attribute 'rjust'", it looks like micro python doesn't support that function, which I found here: https://docs.micropython.org/en/latest/genrst/builtin_types.html?highlight=rjust However, they say that I should be able to use the format() function as a workaround, even though it doesn't seem to be working – gradStudent Jul 18 '22 at 16:01
  • I just figured out a work around, thanks for your help! – gradStudent Jul 18 '22 at 16:16