[Math] Converting Integer to ASCII string

cryptography

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.

Best Answer

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.)

Related Question