How to convert an int to a hex string?

后端 未结 13 667
不知归路
不知归路 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:34

    Let me add this one, because sometimes you just want the single digit representation

    ( x can be lower, 'x', or uppercase, 'X', the choice determines if the output letters are upper or lower.):

    '{:x}'.format(15)
    > f
    

    And now with the new f'' format strings you can do:

    f'{15:x}'
    > f
    

    To add 0 padding you can use 0>n:

    f'{2034:0>4X}'
    > 07F2
    

    NOTE: the initial 'f' in f'{15:x}' is to signify a format string

    0 讨论(0)
  • 2020-11-28 03:34
    (int_variable).to_bytes(bytes_length, byteorder='big'|'little').hex()
    

    For example:

    >>> (434).to_bytes(4, byteorder='big').hex()
    '000001b2'
    >>> (434).to_bytes(4, byteorder='little').hex()
    'b2010000'
    
    0 讨论(0)
  • 2020-11-28 03:35

    Try:

    "0x%x" % 255 # => 0xff
    

    or

    "0x%X" % 255 # => 0xFF
    

    Python Documentation says: "keep this under Your pillow: http://docs.python.org/library/index.html"

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

    This worked best for me

    "0x%02X" % 5  # => 0x05
    "0x%02X" % 17 # => 0x11
    

    Change the (2) if you want a number with a bigger width (2 is for 2 hex printned chars) so 3 will give you the following

    "0x%03X" % 5  # => 0x005
    "0x%03X" % 17 # => 0x011
    
    0 讨论(0)
  • 2020-11-28 03:38

    Also you can convert any number in any base to hex. Use this one line code here it's easy and simple to use:

    hex(int(n,x)).replace("0x","")

    You have a string n that is your number and x the base of that number. First, change it to integer and then to hex but hex has 0x at the first of it so with replace we remove it.

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

    You are looking for the chr function.

    You seem to be mixing decimal representations of integers and hex representations of integers, so it's not entirely clear what you need. Based on the description you gave, I think one of these snippets shows what you want.

    >>> chr(0x65) == '\x65'
    True
    
    
    >>> hex(65)
    '0x41'
    >>> chr(65) == '\x41'
    True
    

    Note that this is quite different from a string containing an integer as hex. If that is what you want, use the hex builtin.

    0 讨论(0)
提交回复
热议问题