简体   繁体   中英

Integer to Alphanumeric string conversion

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM