gpt4 book ai didi

Java byte 将值错误字符串插入到字节

转载 作者:行者123 更新时间:2023-12-01 17:23:01 25 4
gpt4 key购买 nike

我的类有一个成员 myByte,如下所示。

public class ByteClass {
private Byte myByte;
public Byte getMyByte() {
return myByte;
}
public void setMyByte(Byte myByte) {
this.myByte = myByte;
}
}

我的字符串值为FF,我需要将其分配给类(class)成员,我应该怎么做,因为当我尝试它时,我在编译时遇到了错误

类型不匹配:无法从 byte[] 转换为 byte 我知道我不能使用字节数组作为字符串,但我尝试了多种方法来做到这一点,但没有成功。任何想法如何将值 FF 设置为类?

public class ByteHanlder {

public static void main(String[] args) {
String str = "FF";
byte temp = str.getBytes();
Byte write_data = new Byte(temp);
ByteClass byteClass = new ByteClass();
byteClass.setMyByte(temp);
System.out.println(byteClass.getMyByte());
}
}

最佳答案

假设您确实只想存储一个字节,您可以使用:

int value = Integer.parseInt("FF", 16); 
x.setMyByte((byte) value);

现在,如果您在调试器中查看它,则会得到 -1 的值 - 但这只是因为字节已签名,正如其他回答者所指出的那样。如果您想随时查看无符号值,您可以使用:

// Only keep the bottom 8 bits within a 32-bit integer, which ends up
// treating the original byte as an unsigned value.
int value = x.getMyByte() & 0xff;

您仍然可以存储一个字节 - 然后以无符号方式而不是有符号方式解释它。如果您确实只想存储单个字节 - 8 位 - 我建议您不要更改为使用short

话虽如此,仅需要一个字节的可变包装类型有点奇怪......也许您可以向我们提供更多背景信息来说明为什么您需要这个,并且我们也许能够建议更干净的替代方案。

关于Java byte 将值错误字符串插入到字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17248376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com