Skip to content

Instantly share code, notes, and snippets.

@btnguyen2k
Created November 12, 2024 14:06
Show Gist options
  • Select an option

  • Save btnguyen2k/136588e7a7fbc77c7674f7886874304f to your computer and use it in GitHub Desktop.

Select an option

Save btnguyen2k/136588e7a7fbc77c7674f7886874304f to your computer and use it in GitHub Desktop.
[Java] Chuyển số thập nhân sang cơ số 32 - http://goclaptrinh.io/cms/beginner/java-crockford-base32-numbers/
import java.util.Scanner;
public class GocLapTrinh {
static int nhapSoThapPhan(Scanner scanner) {
System.out.print("Nhập số thập phân: ");
return scanner.nextInt();
}
static String nhapSoBase32(Scanner scanner) {
System.out.print("Nhập số ở hệ cơ số 32 (bảng mã Crockford Base32): ");
return scanner.next();
}
static String doiSangBase32(int n) {
String base32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
StringBuilder s = new StringBuilder();
while (n > 0) {
s.insert(0, base32.charAt(n % 32));
n /= 32;
}
return s.toString();
}
static int charToNum(char c) {
c = Character.toUpperCase(c); // chuyển thành ký tự in hoa
switch (c) {
// theo qui định của bảng mã Crockford, chấp nhận ký tự I và L, nhưng chuyển thành số 1
case 'I': case 'L':
c = '1';
break;
// theo qui định của bảng mã Crockford, chấp nhận ký tự O, nhưng chuyển thành số 0
case 'O':
c = '0';
break;
// theo qui định của bảng mã Crockford, chấp nhận ký tự U, nhưng chuyển thành V
case 'U':
c = 'V';
break;
}
String base32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
for (int i = 0; i < 32; i++) {
if (c == base32.charAt(i)) return i;
}
return -1;
}
static int doiSangThapPhan(String s) {
int n = 0;
for (int i = 0; i < s.length(); i++) {
int num = charToNum(s.charAt(i));
if (num == -1) return -1; // có ký tự không hợp lệ!
n = n * 32 + num;
}
return n;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int n = nhapSoThapPhan(scanner);
System.out.println("Số thập phân: " + n + ", chuyển sang hệ cơ số 32: " + doiSangBase32(n));
String s = nhapSoBase32(scanner);
System.out.println("Số ở hệ cơ số 32: " + s + ", chuyển sang thập phân: " + doiSangThapPhan(s));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment