Convert string to integer

  • Using BLE to set a integer variable in my code but i can only write a hex or string value. Hoe do i convert a string or Hex value to an integer?

    Unhandled exception in callback handler
    Traceback (most recent call last):
     File "", line 445, in _mqtt_handler
     File "", line 31, in logger
    TypeError: unsupported types for __ge__: 'bytes', 'int'

  • @misterlisty If it is a string, you can use int:

    val = int("1234") -> 1234
    val = int("ab13", 16) -> 43975

    If it is a hex string, you can use binascii.hexlify(), like

    binascii.hexlify("\x12") -> '12'

    If you want to convert a bytearray with bytes to an integer, you can use int.from_bytes()

    val = int.from_bytes("\x12\x34", "little") --> 4660

    The opposite exists too.

    P.S.: These are standard Python functions. The only problem here might be, that MicoPython may not cover all variants.

Log in to reply

Pycom on Twitter

Looks like your connection to Pycom Forum was lost, please wait while we try to reconnect.