简体   繁体   English

如何将字符串转换为字节?

[英]How to Convert string to byte?

How can I convert a String containing number like "00110011" to bytes using Java? 如何使用Java将包含"00110011"类的数字的字符串转换为字节? I have tried some code as follows- 我已经尝试了一些代码,如下所示:

System.Text.Encoding enc = System.Text.Encoding.ASCII; 
byte[] myByteArray = enc.GetBytes("a text string"); 
string myString = enc.GetString(myByteArray );

Try: 尝试:

int num = Integer.parseInt("00110011", 2);
byte b = (byte)num;

Do you mean convert a binary number expressed as a string to an int? 您的意思是将表示为字符串的二进制数字转换为int吗?

If so, then: 如果是这样,则:

String binaryString = "00110011";
int base = 2;
int decimal = Integer.parseInt(binaryString, base);

Try something like this 试试这个

String str =  "00110011";
byte[] bytes = str.getBytes();

Alternatively you can send an Encoding to getBytes like "UTF-16", so str.getBytes("UTF-16") 另外,您也可以发送编码到getBytes,例如“ UTF-16”,因此str.getBytes("UTF-16")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM