Search code examples
pythondecimalasciispi

How to convert ASCII text to decimal bytes?


I hope you can help.

I am currently looking into the conversion between ASCII character and Decimal (bytes) on a raspberry pi 4b. I am after a code that does the following.

Looks for the users input (text) such as "Hello world" Converts the text given into decimal bytes, and prints the conversion, such as "72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100" Then converts the decimal bytes into ASCII, and printing the text "Hello world" This may seem odd, but being able to see how to make both conversions will allow me to manipulate and change the code for my bigger project.

I need the code to be suitable for a raspberry pi working with python3

Thank you in advance.

I have tried numerous times to get this to work, but seem to be going round in circles. Any help would be appreciated.


Solution

  • Here's one solution:

    # Example string
    text = "Hello World"
    
    # Convert each character to its ASCII decimal value
    ascii_values = [ord(char) for char in text]
    
    print("Converted into Decimals: ",ascii_values)
    
    # Convert each ASCII value back to its character
    text = ''.join([chr(value) for value in ascii_values])
    
    print("Converted nack to ASCII: ",text)
    

    Output:

    Converted into Decimals:  [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
    Converted nack to ASCII:  Hello World