ASCII、字符串的互相转换

package com.wb.test;

import com.wb.exception.NoSuchPort;
import com.wb.exception.NotASerialPort;
import com.wb.exception.PortInUse;
import com.wb.exception.SendDataToSerialPortFailure;
import com.wb.exception.SerialPortOutputStreamCloseFailure;
import com.wb.exception.SerialPortParameterFailure;


public class WriteDemo {
	
	public static void main(String[] args) throws SerialPortParameterFailure, NotASerialPort, NoSuchPort, PortInUse, SendDataToSerialPortFailure, SerialPortOutputStreamCloseFailure {
	
		//ASCII转换为字符串
		String s = "119 110 48 48 48 46 49 48 50 107 103";
        String[]  chars = s.split(" ");
        String a = "";
        for (int i = 0; i < chars.length; i++){
        	a = a +  (char)Integer.parseInt(chars[i]);//拼接值
            System.out.println(chars[i] + "-->:" + (char)Integer.parseInt(chars[i]));
        }
   	 	System.out.println("獲取的值--》:"+a);
       
        
		//字符串转换为ASCII码
        String s2 = "wn000.102kg";
        char[] chars2 = s2.toCharArray();
        for (int i = 0; i < chars2.length; i++){
            System.out.println(" " + chars2[i] + " " + (int)chars2[i] );
        }
		
	}
 
}
//Bytes轉十六进制字符串
	public String Bytes2HexString(byte[] b) {
		String ret = "";
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			ret += hex.toUpperCase();
		}
		return ret;
	}

	//十六进制字符串轉二进制字符串
	public String hexString2binaryString(String hexString) {
		if (hexString == null || hexString.length() % 2 != 0)
			return null;
		String bString = "", tmp;
		for (int i = 0; i < hexString.length(); i++) {
			tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
			bString += tmp.substring(tmp.length() - 4);
		}
		return bString;
	}

猜你喜欢

转载自blog.csdn.net/baidu_35975930/article/details/83509090