Splitting words and encoding to numbers

478 views Asked by At

I'm currently working on a cryptography system that i build in Java. Before the crypto processing, I need to find the most efficient way to do the following:

After I get a string(f.e. 'plaintext"), i need to split it to its letters and encode them to numbers(f.e. 0-25).

After the cryptographic process i need to do the above on the opposite way, so that the encrypted message(encoded in numbers) is decoded to letters and then letters become one word again.

My main goal is to do what I want in the fastest way i can.

1

There are 1 answers

2
Bohemian On BEST ANSWER

Although you can use streams:

str.chars().map(c -> c - 'a') // IntStream of 0-25

Due to stream overheads, a plain loop over the bytes will be fastest:

byte[] bytes = str.getBytes(); // OK, since all chars are in range 0-127
for (int i = 0; i < bytes.length; i++)
    bytes[i] = bytes[i] - 'a';

And the reverse to decrypt/construct:

for (int i = 0; i < bytes.length; i++)
    bytes[i] = bytes[i] + 'a';
String plain = new String(bytes);