简体   繁体   English

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

[英]Coverting String to byte in Java

Having:拥有:

byte temp;

and a String which represents a binary number:和一个代表二进制数的字符串:

String binary = "00100100";

I want to convert this binary number to hex and store it in byte, so: as 00100100 binary equals 24 hex, I want to obtain:我想将此二进制数转换为十六进制并将其存储在字节中,因此:由于 00100100 二进制等于 24 十六进制,因此我想获得:

temp = 24;

or或者

temp = 0x24;

Here's an example这是一个例子

String binary = "00100100";
int value = Integer.parseInt(binary, 2);
System.out.println(value);
System.out.println("0x" + Integer.toHexString(value));

Integer.parserInt(String, int)

Parses the string argument as a signed integer in the radix specified by the second argument.将字符串参数解析为第二个参数指定的基数中的有符号整数。

So it will convert the binary String value to an integer with the specified base.因此它将二进制字符串值转换为具有指定基数的整数。

You can then use the Integer.toHexString(int) method to convert that value to a hex representation, appending the 0x if you really want to.然后,您可以使用Integer.toHexString(int)方法将该值转换为十六进制表示,如果您真的想要附加0x

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

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