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 "main.py", line 445, in _mqtt_handler
     File "boot.py", line 31, in logger
    TypeError: unsupported types for __ge__: 'bytes', 'int'


  • @robert-hh said in Convert string to integer:

    binascii.hexlify("\x12")

    On my gpy binascii.hexlify("\x12") gives b'12' Rob. How come I get bytes but you get a hex string?



  • Without the 0x prefix, you need to specify the base explicitly, otherwise there's no way to tell:

    x = int("deadbeef", 16)

    With the 0x prefix, Python can distinguish hex and decimal automatically.

    print int("0xdeadbeef", 0)
    3735928559



  • @robert-hh, it worked, thank you.



  • @jclo13
    I assume that the first time you called nvs_get the key 'i' did not exist, and the call returned None, which caused the error at the second line. So you will need something like:

    import pycom
    i = pycom.nvs_get('i')
    if i is not None:
        pycom.nvs_set('i', i+1)
    else:
        pycom.nvs_set('i', 0)
    

    You could as well write it with a ternary expression:

    import pycom
    i = pycom.nvs_get('i')
    pycom.nvs_set('i', 0 if i is None else i+1)
    


  • hello @robert-hh

    I have this error:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unsupported types for __add__: 'NoneType', 'int'
    

    I want to use a counter whit the deepsleep, and I am using

    i = pycom.nvs_get('i')
    pycom.nvs_set('i', i+1)
    
    

    Is there a way to make to counter?

    Thank You in advance.

    Jose



  • @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