在Java中将字符转换为字节,字符串转换为字节

时间:2018-05-03 01:41:59

标签: java

我一直在使用套接字发送数据,发送的数据是带有消息结构的ASCII协议。消息的结构位于此链接https://imgur.com/a/odVQk5X中。这是我到目前为止编写的代码。

Socket socket = new Socket(host, port);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.write(byte_array); //Send data to the socket
out.flush();

String reply = in.readLine(); //Read for any response returned by the server
System.out.println("Reply from Server: " + reply);

我的问题是,在发送之前,在将字符串发送到字节之前,有替代方法而不是将字符转换为字节。这是在将其发送到套接字之前的当前转换代码。

byte[] byte_array = new byte[] {7, charToByte('0'), charToByte('5'), charToByte('N'), charToByte('R'), charToByte('X'), 13};
public static byte charToByte(char a)
{
    return (byte)(a & 0xFF);
}

所以基本上我想知道是否有办法将字符串“\ a01NIP \ r \ n”转换为字节,因为我已经尝试了getBytes(),但我得到的结果是“从服务器回复:null”。 / p>

0 个答案:

没有答案
相关问题