如何将长度为3的Base62字符串反向转换为原始整数?
Absolutely! You can definitely reverse this Base62 encoding to get back your original integer—since it's a fixed-length, one-to-one mapping between integers and 3-character strings, the process is straightforward. Here's how to make it work, tailored to your example where "zzz" maps back to 238328.
How the Reverse Process Works
Your encoding uses a 62-character set (0-9, A-Z, a-z), where each position in the 3-character string has a weight based on powers of 62:
- The first (leftmost) character has a weight of
62²(3844) - The second character has a weight of
62¹(62) - The third (rightmost) character has a weight of
62⁰(1)
For a string like "zzz", each 'z' is the 61st index in your CHARACTERS string (since we start counting from 0). The raw Base62 value would be:61*3844 + 61*62 + 61 = 238327
Since your encoding maps 238328 to "zzz", it’s likely adding 1 to the raw Base62 value during encoding. So we just need to reverse that step in decoding.
Java Implementation for Decoding
Here’s a complete decoding method that matches your original encoding setup:
private static final String CHARACTERS = "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz"; public static int decodeBase62(String encoded) { // Validate input length matches your fixed 3-character requirement if (encoded.length() != 3) { throw new IllegalArgumentException("Encoded string must be exactly 3 characters long"); } int baseValue = 0; for (int i = 0; i < encoded.length(); i++) { char currentChar = encoded.charAt(i); int charIndex = CHARACTERS.indexOf(currentChar); // Handle invalid characters not present in your encoding set if (charIndex == -1) { throw new IllegalArgumentException("Invalid character in encoded string: " + currentChar); } // Calculate the contribution of the current character to the total value baseValue += charIndex * (int) Math.pow(62, 2 - i); } // Adjust for the +1 offset used in your encoding (since 238327 +1 = 238328) return baseValue + 1; }
Testing the Example
If you run decodeBase62("zzz"), it will return 238328—exactly the integer you started with.
Key Notes to Avoid Issues
- Keep the CHARACTERS string identical: The order of characters (digits first, then uppercase, then lowercase) must match exactly what’s used in your encoding code. Changing the order will break the mapping.
- Input validation: Always check that the input string is 3 characters long and only contains valid characters from your set.
- Offset adjustment: If your original encoding doesn’t use a +1 offset (e.g., 238327 maps to "zzz"), just remove the
+1in the return statement.
内容的提问来源于stack exchange,提问作者cubeb

