Java - Change int to ascii

前端 未结 7 851
迷失自我
迷失自我 2020-12-01 07:32

Is there a way for java to convert int\'s to ascii symbols?

相关标签:
7条回答
  • 2020-12-01 08:06

    In Java, you really want to use Integer.toString to convert an integer to its corresponding String value. If you are dealing with just the digits 0-9, then you could use something like this:

    private static final char[] DIGITS =
        {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    
    private static char getDigit(int digitValue) {
       assertInRange(digitValue, 0, 9);
       return DIGITS[digitValue];
    }
    

    Or, equivalently:

    private static int ASCII_ZERO = 0x30;
    
    private static char getDigit(int digitValue) {
      assertInRange(digitValue, 0, 9);
      return ((char) (digitValue + ASCII_ZERO));
    }
    
    0 讨论(0)
  • 2020-12-01 08:11

    The most simple way is using type casting:

    public char toChar(int c) {
        return (char)c;
    }
    
    0 讨论(0)
  • 2020-12-01 08:12

    You can convert a number to ASCII in java. example converting a number 1 (base is 10) to ASCII.

    char k = Character.forDigit(1, 10);
    System.out.println("Character: " + k);
    System.out.println("Character: " + ((int) k));
    

    Output:

    Character: 1
    Character: 49
    
    0 讨论(0)
  • 2020-12-01 08:17

    Do you want to convert ints to chars?:

    int yourInt = 33;
    char ch = (char) yourInt;
    System.out.println(yourInt);
    System.out.println(ch);
    // Output:
    // 33
    // !
    

    Or do you want to convert ints to Strings?

    int yourInt = 33;
    String str = String.valueOf(yourInt);
    

    Or what is it that you mean?

    0 讨论(0)
  • 2020-12-01 08:20

    There are many ways to convert an int to ASCII (depending on your needs) but here is a way to convert each integer byte to an ASCII character:

    private static String toASCII(int value) {
        int length = 4;
        StringBuilder builder = new StringBuilder(length);
        for (int i = length - 1; i >= 0; i--) {
            builder.append((char) ((value >> (8 * i)) & 0xFF));
        }
        return builder.toString();
    }
    

    For example, the ASCII text for "TEST" can be represented as the byte array:

    byte[] test = new byte[] { (byte) 0x54, (byte) 0x45, (byte) 0x53, (byte) 0x54 };
    

    Then you could do the following:

    int value = ByteBuffer.wrap(test).getInt(); // 1413829460
    System.out.println(toASCII(value)); // outputs "TEST"
    

    ...so this essentially converts the 4 bytes in a 32-bit integer to 4 separate ASCII characters (one character per byte).

    0 讨论(0)
  • 2020-12-01 08:21

    In fact in the last answer String strAsciiTab = Character.toString((char) iAsciiValue); the essential part is (char)iAsciiValue which is doing the job (Character.toString useless)

    Meaning the first answer was correct actually char ch = (char) yourInt;

    if in yourint=49 (or 0x31), ch will be '1'

    0 讨论(0)
提交回复
热议问题