Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

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.

share|improve this question
1  
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
add comment

2 Answers

up vote 0 down vote accepted

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.

share|improve this answer
    
It isn't "similar to changing bases", it is changing bases. –  vonbrand Mar 6 at 19:21
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.