怎么把string转换为字节byte
时间: 2023-04-01 18:00:46 浏览: 71
可以使用getBytes()方法将string转换为字节数组byte[]。例如,如果要将字符串str转换为字节数组,可以使用以下代码:
String str = "Hello World";
byte[] bytes = str.getBytes();
相关问题
C#将string转换为字节数组
可以使用以下代码将字符串转换为字节数组:
```csharp
string str = "hello world";
byte[] bytes = Encoding.UTF8.GetBytes(str);
```
这里使用了`Encoding.UTF8.GetBytes()`方法将字符串转换为字节数组。如果要使用其他编码方式,只需要将`Encoding.UTF8`替换为相应的`Encoding`对象即可。
使用java String 转换为byte数组
在Java中,可以使用String类的`getBytes()`方法将字符串转换为字节数组。这个方法会将字符串中的每个字符转换为对应的字节,并返回结果字节数组。
以下是一个示例代码:
```java
String str = "Hello, World!";
byte[] byteArray = str.getBytes(); // 将字符串转换为字节数组
// 打印字节数组中的每个元素
for (byte b : byteArray) {
System.out.print(b + " ");
}
```
输出结果将会是每个字符对应的字节值,例如:
```
72 101 108 108 111 44 32 87 111 114 108 100 33
```
请注意,`getBytes()`方法默认使用平台的默认字符集进行编码。如果想要指定使用其他字符集,可以在`getBytes()`方法中传入对应的字符集参数。例如,`str.getBytes("UTF-8")`会使用UTF-8字符集进行编码。