javaarraysstring

How to translate a char array into a long and back in Java (not Long.parseLong() or String.valueOf())


I am trying to make a cryptography program using RSA, and need to be able to turn plaintext into a long. Obviously the plaintext would have to have more than just numbers in it, so using Long.parseLong() is not a solution. I found this and it explained how to convert a char array into a long in this way, but am unsure of how to translate it back to a char array (or String). The code I got from the above website is here:

public long charArrayToLong(char[] bi){
    long len = bi.length;
    long sum = 0;
    long tmp, max = len - 1;
    for (int i = 0; i < len; ++i) {
        tmp = bi[i] - '0';
        sum += tmp * Math.pow(2, max--);
    return sum;
}

This code works to translate a char array into a long without depending on only numerical values being in the char array, but I also need a method of converting it back.

Specifically what I'm looking for is this: I need to convert each char in a String into a number, based on its ASCII value, multiply that number based on a power of its location in the String, add those numbers together to get a long plaintext variable, and reverse the operation to translate it the other way.

My expected input is a String in plaintext (e.g. "The quick brown fox jumps over the lazy dog"). My expected output is a long with values for each character in the String embedded in the number.

The reason I need to do this is because I need to exponentiate a number, not a String, with the formula c = m ^ e % n. Since m is the message in plaintext, I need it to be converted into a number so I can take it to the power of e, the public key.


Solution

  • // Convert String to long
    public static long stringToLong(String s) {
        long result = 0;
        for (char c : s.toCharArray()) {
            result = (result << 8) + c;
        }
        return result;
    }
    
    // Convert long back to String
    public static String longToString(long value) {
        StringBuilder sb = new StringBuilder();
        while (value > 0) {
            sb.insert(0, (char)(value & 0xFF));
            value >>= 8;
        }
        return sb.toString();
    }
    

    Bit Shifting!