Cristina
Cristina

Reputation: 31

How to keep ASCII value in normal string?

I'm working on converting an integer value to a high/low message like this:

def int2message(integer):
    messageHigh=chr(integer//256)
    messageLow=chr(integer%256)
    return [str(messageHigh),str(messageLow)]

and here is the example:

>>testValue=int2message(10)
>>print(testValue)
['\x00', '\n']

Now, I want to append this result to the end of the list like this:

['0xA2', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '00', '0n']
                                                        |     |
                                                       high  low

but I find that it's hard to save ASCII values as a normal string. I can't use replace() to delete \x and \ and other operations of normal strings.

When I print \x00 and \n separately, they are invisible.

Is there any good idea to deal with this problem? And is there any better format to convert integer values to normal strings?

Upvotes: 1

Views: 653

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 149185

Assuming you are using ASCII or one of its 8bit derivatives (to be able to print all code points below 256), you must know that:

  • all code points below 32 are control characters. Specifically '\x00' is the NULL character and '\x0a' (or '\n') is LineFeed
  • character '\x20' (32) is the space character
  • only code points between 33 ('!') and 126 ('~') are normal printable ASCII characters
  • character 127 is the DEL (not printable) character
  • character from 128 to 255 have different representation depending on the charset. For example '\xe9' prints as é in Latin1 charset and 'Ú' in CP850 charset

Said differently, you can store any value below 256 in characters (or bytes in Python 3), but you cannot print them directly. Convert them in hexa with hex or in their decimal value string with str if you want to print them.

Upvotes: 1

Pam
Pam

Reputation: 1163

Partial answer, I'm afraid as I'm not entirely clear on what you want output. The decimal number 10 gives the ASCII character \n (which is a line feed). I assume that when you convert that to a string, you want an invisible line feed (and not any actual character output). Making the following adjustments will give you that.

def int2message(integer):
    messageHigh=chr(integer//256)
    messageLow=chr(integer%256)
    return [str(messageHigh),str(messageLow)]


testValue=int2message(10)
testValue = bytearray(testValue)
print(testValue)

Output is simply a space followed by a line feed (so the cursor moves but no text is output).

Upvotes: 0

Related Questions