Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert integers to base64 (0-9A-Za-z)

I have been trying to reduce the length of the way. I represent some integer ID's in my program. For Example

2
3
15
26
63
...
151564852

I would like them to be represented as such (0-9A-Za-z only)

2
3
F
Q
z
...
vDF25a   //For example

The approach I thought of is to have 63 if statements which each of the mappings from 0-63 to 0-z respectively and for anything above 64 do a recursion on the value minus 63.

Needless to say, I think my approach is very flawed and impractical. What would be a more appropriate way of doing it?


Update:

Following fge's suggestion I've got the encoder to work correctly, however my decode function only works for up-to length 2 strings, in cases where the string is larger the sum becomes erroneous. For example for 3840 to 3845 this is the output

// Encoded 
zw
x
zy
zz
100

// Decoded
3840
3841
3842
3843
124         //Invalid decoding

Here is my code for the decode function

public static int decode(String value)
{
    String revStr = new StringBuilder(value).reverse().toString();

    int sum = 0;



    for (int i=1; i < revStr.length(); i++)
    {
        for (int j=0; j < ALPHABET.length; j++)
        {
            if (ALPHABET[j] == revStr.charAt(i))
            {
                sum += (ALPHABET.length * j) * i;
                break;
            }
        }
    }

    for (int j=0; j < ALPHABET.length; j++)
    {
        if (ALPHABET[j] == revStr.charAt(0))
        {
            sum += j;
            break;
        }
    }

    return sum;
}
like image 588
pondigi Avatar asked Feb 26 '14 13:02

pondigi


2 Answers

This is not base64; base64 encodes binary data.

Anyway, you don't need a s*load of if statements; use an array:

public final class AlphabetEncoder
{
    private static final char[] ALPHABET = { '0', '1', '2', ...., 'z' };
    private static final int ENCODE_LENGTH = ALPHABET.length;

    public static String encode(int victim)
    {
        final List<Character> list = new ArrayList<>();

        do {
            list.add(ALPHABET[victim % ENCODE_LENGTH]);
            victim /= ENCODE_LENGTH;
        } while (victim > 0);

        Collections.reverse(list);
        return new String(list.toArray(new char[list.size()],
            StandardCharsets.UTF_8);
    }

    public int decode(final String encoded)
    {
        int ret = 0;
        char c;
        for (int index = 0; index < encoded.length(); index++) {
            c = encoded.charAt(index);
            ret *= ENCODE_LENGTH;
            ret += Arrays.binarySearch(ALPHABET, c);
       }
       return ret;
    }
}

NOTE ABOUT THE DECODE FUNCTION: it is possible to use Arrays.binarySearch() here since the alphabet has the nice property of being naturally sorted (0 < 1 < 2 < ... < z). However, a test should probably be added that its return code not be negative!

like image 101
fge Avatar answered Oct 05 '22 18:10

fge


Depending on the language you use, there should already be a module which converts a string from/to base64. Check this other post: Base64 Encoding in Java

like image 32
ctutte Avatar answered Oct 05 '22 20:10

ctutte