473,396 Members | 2,087 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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:

http://bytes.com/topic/python/answer...-decimal-value

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

Thanks for your help! :]
Sep 7 '10 #1

✓ answered by bvdet

This works for your example:
Expand|Select|Wrap|Line Numbers
  1. >>> def numToWord(n):
  2. ...     hexvalue = hex(n)[2:]
  3. ...     return "".join([chr(int(s, 16)) for s in [hexvalue[i:i+2] for i in range(0,len(hexvalue),2)]])
  4. ... 
  5. >>> numToWord(1650811246)
  6. 'bean'
  7. >>> 

9 8758
bvdet
2,851 Expert Mod 2GB
This works for your example:
Expand|Select|Wrap|Line Numbers
  1. >>> def numToWord(n):
  2. ...     hexvalue = hex(n)[2:]
  3. ...     return "".join([chr(int(s, 16)) for s in [hexvalue[i:i+2] for i in range(0,len(hexvalue),2)]])
  4. ... 
  5. >>> numToWord(1650811246)
  6. 'bean'
  7. >>> 
Sep 7 '10 #2
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!
Sep 7 '10 #3
bvdet
2,851 Expert Mod 2GB
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?
Sep 7 '10 #4
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.
Sep 7 '10 #5
bvdet
2,851 Expert Mod 2GB
You can pad the hex string with a leading '0' if the length of the string is an odd number.
Expand|Select|Wrap|Line Numbers
  1. def numToWord(n):
  2.     '''Convert integer number n to hex value to an ascii word.'''
  3.     hexvalue = hex(n)[2:]
  4.     # if string length is an odd number, pad with a leading '0'
  5.     if len(hexvalue) % 2:
  6.         hexvalue = '0' + hexvalue
  7.     return "".join([chr(int(s, 16)) for s in [hexvalue[i:i+2] for i in range(0,len(hexvalue),2)]])
Sep 8 '10 #6
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).
Sep 8 '10 #7
bvdet
2,851 Expert Mod 2GB
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.
Expand|Select|Wrap|Line Numbers
  1. def numToWord(n):
  2.     '''Convert integer number n to hex value to an ascii word.'''
  3.     # pad hexvalue with leading space characters
  4.     hexvalue = "%8s" % (hex(n)[2:].rstrip('L'))
  5.     output = []
  6.     for i in range(0,len(hexvalue),2):
  7.         # strip leading space characters
  8.         s = hexvalue[i:i+2].lstrip()
  9.         if s:
  10.             output.append(chr(int(s, 16)))
  11.     return "".join(output)
Sep 8 '10 #8
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?
Sep 8 '10 #9
bvdet
2,851 Expert Mod 2GB
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:
Expand|Select|Wrap|Line Numbers
  1. hexvalue = hexvalue.replace(" ", "0")
Sep 8 '10 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Hessam | last post by:
Hello, I am designing a .net custom control in VS.net 7.1 and my control exposes an array of strings which are supposed to be the items to show. To do this have declared a private string variable...
0
by: Hessam | last post by:
Hello, I am designing a .net custom control in VS.net 7.1 and my control exposes an array of strings which are supposed to be the items to show. To do this have declared a private string variable...
3
by: Convert TextBox.Text to Int32 Problem | last post by:
Need a little help here. I saw some related posts, so here goes... I have some textboxes which are designed for the user to enter a integer value. In "old school C" we just used the atoi function...
4
by: Ken Varn | last post by:
I have an unknown numeric Type object passed into a function. I want to run a conversion on a string to convert the string to that Type object and return an object of that type. Is there some way...
15
by: Yifan | last post by:
Hi Does anybody know how to convert System::String* to char*? I searched the System::String class members and did not find any. Thanks Yifan
13
by: HNT20 | last post by:
Hello All i am new to python language. i am working on a gnuradio project where it uses python as the primary programming language. i am trying to convert a message, text, or numbers into binary...
0
by: Rajesh soni | last post by:
hi friends i got an error while building a web control.... this error is as follows. "Cannot create an object of type 'System.String' from its string representation 'String Array' for the...
3
by: priyanka | last post by:
Hi there, I want to convert a String into integer. I get the string from a file using : string argNum; getline(inputStream,argNum); I now need to convert argNum into integer.
1
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - Why does 1+1 equal 11? or How do I convert a string to a number?...
6
by: Deckarep | last post by:
I want to be able to pass in a function a string say: "TextBox" Then I need a way to convert that string representation into a Type object so i can search through some controls and check their...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.