How to convert an int to a hex string?

后端 未结 13 665
不知归路
不知归路 2020-11-28 03:27

I want to take an integer (that will be <= 255), to a hex string representation

e.g.: I want to pass in 65 and get out \'\\x41\', or

相关标签:
13条回答
  • 2020-11-28 03:41

    This will convert an integer to a 2 digit hex string with the 0x prefix:

    strHex = "0x%0.2X" % 255
    
    0 讨论(0)
  • 2020-11-28 03:41

    What about hex()?

    hex(255)  # 0xff
    

    If you really want to have \ in front you can do:

    print '\\' + hex(255)[1:]
    
    0 讨论(0)
  • 2020-11-28 03:41

    I wanted a random integer converted into a six-digit hex string with a # at the beginning. To get this I used

    "#%6x" % random.randint(0xFFFFFF)
    
    0 讨论(0)
  • 2020-11-28 03:41

    As an alternative representation you could use

    [in] '%s' % hex(15)
    [out]'0xf'
    
    0 讨论(0)
  • 2020-11-28 03:42

    If you want to pack a struct with a value <255 (one byte unsigned, uint8_t) and end up with a string of one character, you're probably looking for the format B instead of c. C converts a character to a string (not too useful by itself) while B converts an integer.

    struct.pack('B', 65)
    

    (And yes, 65 is \x41, not \x65.)

    The struct class will also conveniently handle endianness for communication or other uses.

    0 讨论(0)
  • 2020-11-28 03:51

    With format(), as per format-examples, we can do:

    >>> # format also supports binary numbers
    >>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
    'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
    >>> # with 0x, 0o, or 0b as prefix:
    >>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
    'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'
    
    0 讨论(0)
提交回复
热议问题