package main;
/**
* Convert a character to the corresponding Ascii code in Java
* 1 byte = 8bit can represent 0-127
*/
public class GetCharAscii { /*0-9 corresponds to Ascii 48-57 *AZ 65-90 * az 97-122 *No. 33~126 (94 in total) are characters, of which No. 48~57 are 0~9 ten Arabic numerals */ public static void main(String[] args) { // TODO Auto- generated method stub System.out.println(charToByteAscii('9')); System.out.println(byteAsciiToChar(57)); System.out.println(SumStrAscii("19")); System.out.println(SumStrAscii ("一")); } /** * Method 1: Cast char to byte * @param ch * @return
*/
public static byte charToByteAscii(char ch){ byte byteAscii = (byte)ch; return byteAscii; } /** * Method 2: Convert char directly to int, and its value is the ascii of the character * @param ch * @return */ public static byte charToByteAscii2(char ch){ byte byteAscii = (byte)ch; return byteAscii; } /** * In the same way, ascii is converted to char and directly int is forcibly converted to char * @param ascii * @return */ public static char byteAsciiToChar(int ascii){ char ch = (char)ascii; return ch; } /**
* Find the ASCII value of the string and
* Note that if there is Chinese, a Chinese character will be represented by two bytes, and its value is a negative number
*/
public static int SumStrAscii(String str){ byte[] bytestr = str. getBytes(); int sum = 0; for(int i=0;i<bytestr.length;i++){ sum += bytestr[i]; } return sum; } }
Corresponding conversion between char and number
Guess you like
Origin blog.csdn.net/xiaolegeaizy/article/details/114186423
Ranking