0

I need to convert five digit integer to alphanumeric string of length 5.Doing below but sometimes it doesn't provide alphanumeric but numeric value.

Long x = 12345L;
String code = Long.toHexString(x).toUpperCase();

I want to get Alphanumeric string of length 5 always.

4
  • What do you mean by "alphanumeric value"? You want to convert it to String? Commented Feb 22, 2016 at 8:35
  • Let say for Ex:- 12345 --> A12BC Commented Feb 22, 2016 at 8:36
  • What are the rules? Why 12345 turns into A12BC? Commented Feb 22, 2016 at 8:36
  • As such there are no rules,from client side i will generate some TOTP of five digit and then convert it to alphanumeric string of same length and then this data will travel through to backend,and on back end side similar TOTP logic will run and will again generate alphanumeric string. I am doing this just to encode this numeric value,i have space constraint because of vendor,only 5 character are permitted. Commented Feb 22, 2016 at 8:41

2 Answers 2

2

Try this

static String alphaNumric(int value) {
    String s = "abcde" + Integer.toString(value, 36);
    return s.substring(s.length() - 5);
}

and

    int[] tests = { 12345, 1, 36, 36 * 36, 32767, 99999 };
    for (int i : tests)
        System.out.println(i + " -> " + alphaNumric(i));

output

12345 -> de9ix
1 -> bcde1
36 -> cde10
1296 -> de100
32767 -> depa7
99999 -> e255r
Sign up to request clarification or add additional context in comments.

Comments

0

That's hardly surprising.

For example, 0x12345 is 74565, so 74565 does not contain any of the digits A to F when converted to hexadecimal.

Given that 99999 is 0x1869F, you have plenty of room in your converted string to accommodate some "junk" data, consider introducing an additive constant (0xA0000 perhaps which at least guarantees at least one alpha character for positive inputs), or even a number that your XOR with your original.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.