# Converting Integer to ASCII string

I was reading up on how to convert strings to integer representations for RSA encryption. See this link. Basically, the string-to-integer conversion goes as follows:

a(char_1)*256^n + a(char_2)*256^(n-1) + ... + a(char_n)*256^0


where

n = string length
a(char) = ASCII representation of the character


My question is how you would convert from the integer back to the original string. This link says to perform the inverse of the original algorithm, but I don't know how I would go about doing that.

-
You seem to have $n+1$ characters, not $n$, if they go from $0$ to $n$. – Robert Israel Oct 21 '12 at 5:50
You're right. It should be 1 to n. – Azmisov Oct 21 '12 at 6:24

Given a value such as $1415934836.00$ and an expression such as:

$$(x_{3})*256^3+(x_{2})*256^2+(x_{1})*256^1+(x_{0})*256^0=1415934836.00$$

You can perform the iterations below to get the values $x_{i}$ from the second column of the table below (where base=256)

Value          Int(Value/Base)  Mod(Value/Base)

1415934836.00  5530995.00       116.00

5530995.00     21605.00         115.00

21605.00       84.00            101.00

84.00          0.00             84.00


So we get:

$$(84)*256^3+(101)*256^2+(115)*256^1+(116)*256^0=1415934836.00$$

Notice how similar this is to converting numbers between bases.

-
It isn't "similar to changing bases", it is changing bases. – vonbrand Mar 6 '14 at 19:21

Multiplying by $256=2^8$ is equivalent to a left shift of $8$ bits. To invert, you basically unshift the bits out, so to speak.

To illustrate, suppose $i$ is the integer. Then, to recover $\text{char_n}$, just take $\text{char_n} = i \,\text{%}\, 256$. To recover $\text{char_n-1}$, do something like $\text{char_n-1} = (i \text{>>} 8) \,\text{%}\, 256$. The pattern should be clear from this.

($\,\text{%}\,$ is the $\mathbb{mod}$ operator, and $\text{>>}$ is the right shift operator.)

-