Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将字符串转换为字节[]数组_Java_String_Type Conversion_Byte - Fatal编程技术网

Java 将字符串转换为字节[]数组

Java 将字符串转换为字节[]数组,java,string,type-conversion,byte,Java,String,Type Conversion,Byte,我想将字符串转换为字节数组,但数组必须有256个位置,我的意思是,如下所示: public byte[] temporal1 = new byte[256]; public byte[] temporal2 = new byte[256]; 因此,当我这样做时: String send = "SEND_MESSAGE"; String sendAck = "SEND_MESSAGE_ACK"; temporal1 = send.getBytes(); temporal2 = sendAck.g

我想将字符串转换为字节数组,但数组必须有256个位置,我的意思是,如下所示:

public byte[] temporal1 = new byte[256];
public byte[] temporal2 = new byte[256];
因此,当我这样做时:

String send = "SEND_MESSAGE";
String sendAck = "SEND_MESSAGE_ACK";
temporal1 = send.getBytes();
temporal2 = sendAck.getBytes();

我得到这个错误:“/th.java:24:error:expected”。我知道如果我做了
publicbyte[]temporal1=send.getBytes()它可以工作,但我需要具有该大小的数组与其他字节数组逐字节进行比较。

能否请您显示控制台中发生的确切异常或错误。因为它对我来说非常好

byte b1[] = new byte[256];
String s = "hello there";
b1 = s.getBytes();
System.out.println(b1);

要将字节数组
temporal1
填充到256字节,可以执行以下操作:

public byte[] temporal1 = new byte[256];
String send = "SEND_MESSAGE";
byte[] sendB = send.getBytes(send, StandardCharsets.UTF_8);
System.arraycopy(sendB, 0, temporal1, 0, Math.max(256, sendB.length));
如果您想要一个类似于C的终止0字节的方法,sendB只能提供255字节:
Math.max(255,sendB.length)

更好:

String send = "SEND_MESSAGE";
byte[] sendB = send.getBytes(send, StandardCharsets.UTF_8);
byte[] temporal1 = Arrays.copyOf(sendB, 256); // Pads or truncates.
temportal1[255] = (byte) 0; // Maybe

要从具有定义大小的
字符串
获取
字节[]

public static byte[] toBytes(String data, int length) {
    byte[] result = new byte[length];
    System.arraycopy(data.getBytes(), 0, result, length - data.length(), data.length());
    return result;
}
Ex:
byte[]sample=toBytes(“发送消息”,256)


示例
的大小将为256。

为什么不使用btye[]b1=新字节[256]?我得到了这个错误“/th.java:24:error:expected”但是没关系。。。帕特里克·帕克解决了我的问题;)@当然,你也可以使用
byte[]b1
这两者没有区别。但是按照您的建议使用
byte[]b1
,这样可以在阅读核心时更好地理解声明的数据类型是一个数组,是的,我的错,对不起:如果我的源字节[]没有256个字节(它有上面的选项),那么用
(byte)填充256个字节的数组结尾处0
s。在另一端接收时可以对其进行修剪。我还没有尝试代码的第二个块。但是如果源代码没有256字节,第一个块会抛出错误。我想在开始处添加0比在结尾处添加更有用。
temporal1
是256字节数组;为源代码发送临时数组字符串的转换。我只能猜测零。