How do you convert a hex representation into a string?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • darktemp
    New Member
    • Feb 2010
    • 25

    How do you convert a hex representation into a string?

    I have a small program that converts a set of decimal numbers into string. What I can do is convert it from decimal to hexadecimal then to string, but I have the feeling there is a more easier way of doing it. For example:

    '1650811246' is the number I am given. The output should be 'bean'. The hexadecimal representation should be '6265616E'.

    All my strings and hexadecimal representations of the numbers will be in a set of four if that helps.

    This is essentially the reverse way of what I asked before in this thread:



    It will start with a number and give me a 4-length string.

    Thanks for your help! :]
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    This works for your example:
    Code:
    >>> def numToWord(n):
    ... 	hexvalue = hex(n)[2:]
    ... 	return "".join([chr(int(s, 16)) for s in [hexvalue[i:i+2] for i in range(0,len(hexvalue),2)]])
    ... 
    >>> numToWord(1650811246)
    'bean'
    >>>

    Comment

    • darktemp
      New Member
      • Feb 2010
      • 25

      #3
      Thanks for the prompt reply! I tried your method and it works great, can it be modified in a way where single digits/characters in hex have a zero preceding it?

      Hex value of '5' will be '05' instead. I was thinking of string manipulating it but I don't want all of the first hex values to have a zero preceding it.

      Thanks!

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Do you have a single integer (1650811246) or a set of integers? An integer cannot be preceded with a zero, but a string can. Can you be more specific?

        Comment

        • darktemp
          New Member
          • Feb 2010
          • 25

          #5
          I'll use this example:

          Say I have a number 91000465, its hex value would have to be 056c8e91 and when it becomes a string it would be a 4 character string of the representation of 05, 6c, 8e, and 91. The method you gave me does this fine but it shows '56c8e91' instead of '056c8e91'. Showing the first would cause a bug in translating it to string as it would get the first character for hex 56, then c8, then e9, and then 1. Also to note, any hex values that are single digit/character would have to have a 0 in front of it to be able to convert to its string representation correctly. Oh and the 4 letter string is strict (it has to be 4 letters long or the program crashes) so if the number translates hex values with NUL characters, it has to show 00 in it and if it translates 00 00 00 05, it will have to have the first three NUL as well.

          Hope that helps.

          Comment

          • bvdet
            Recognized Expert Specialist
            • Oct 2006
            • 2851

            #6
            You can pad the hex string with a leading '0' if the length of the string is an odd number.
            Code:
            def numToWord(n):
                '''Convert integer number n to hex value to an ascii word.'''
                hexvalue = hex(n)[2:]
                # if string length is an odd number, pad with a leading '0'
                if len(hexvalue) % 2:
                    hexvalue = '0' + hexvalue
                return "".join([chr(int(s, 16)) for s in [hexvalue[i:i+2] for i in range(0,len(hexvalue),2)]])

            Comment

            • darktemp
              New Member
              • Feb 2010
              • 25

              #7
              Hello again, the improved method you suggested did fix issues with hex values that had single digits/characters but is there a way to make the hex value output a line of leading zeros? The 4 length string requirement is strict otherwise the program crashes if the decimal value is small. I was thinking of padding it, but there is no way to know how many leading zeros there are, at most there is only 7, but can range from 0-7.

              Example:
              If the decimal value is 1, the hex must be 00 00 00 01 and the string must output NUL NUL NUL (whatever 1 is in hex).

              Comment

              • bvdet
                Recognized Expert Specialist
                • Oct 2006
                • 2851

                #8
                Why pad with "0" characters as an intermediate step? String formatting can pad with space characters. Then you can strip any leading space characters and evaluate each character pair for True or False.
                Code:
                def numToWord(n):
                    '''Convert integer number n to hex value to an ascii word.'''
                    # pad hexvalue with leading space characters
                    hexvalue = "%8s" % (hex(n)[2:].rstrip('L'))
                    output = []
                    for i in range(0,len(hexvalue),2):
                        # strip leading space characters
                        s = hexvalue[i:i+2].lstrip()
                        if s:
                            output.append(chr(int(s, 16)))
                    return "".join(output)

                Comment

                • darktemp
                  New Member
                  • Feb 2010
                  • 25

                  #9
                  Can 'hexvalue' be padded with NUL then?

                  What I am trying to do is write to a file in which my other program pulls information out of it. The information is stored in a 4 byte cell block. Spaces would make the hex representation 30 which would change the value of the stored number so would it be possible to store it as NUL instead of spaces?

                  Comment

                  • bvdet
                    Recognized Expert Specialist
                    • Oct 2006
                    • 2851

                    #10
                    You can store it with any character you want instead of spaces. Simply replace each space character in the string with the character you want. Example:
                    Code:
                    hexvalue = hexvalue.replace(" ", "0")

                    Comment

                    Working...