java中如何将一个字符转换为ascii码

方法1:
char c = ‘a ‘;
byte b =(byte)c;
方法2:
直接将这个字符转化为int型就可以得到ascii码值搜索
char c = ‘a ‘;
int b = c; //字符的ascii码值
同理将一个ascii码转换为相应的字符:
例如:字符a
int d = 97;
char e = (char)d;

 

将字符串转成ASCII

    /**
     * 字符串转换为Ascii
     * @param value
     * @return
     */
    public static String stringToAscii(String value)  
    {  
        StringBuffer sbu = new StringBuffer();  
        char[] chars = value.toCharArray();   
        for (int i = 0; i < chars.length; i++) {  
            if(i != chars.length - 1)  
            {  
                sbu.append((int)chars[i]).append(",");  
            }  
            else {  
                sbu.append((int)chars[i]);  
            }  
        }  
        return sbu.toString();  

}

将ASCII转成字符串

    /**
     * Ascii转换为字符串
     * @param value
     * @return
     */
    public static String asciiToString(String value)
    {
        StringBuffer sbu = new StringBuffer();
        String[] chars = value.split(",");
        for (int i = 0; i < chars.length; i++) {
            sbu.append((char) Integer.parseInt(chars[i]));
        }
        return sbu.toString();
    }

发表评论