How to Convert Int to Unsigned Byte and Back(如何将 Int 转换为无符号字节并返回)
问题描述
我需要将数字转换为无符号字节.该数字始终小于或等于 255,因此它可以容纳在一个字节中.
I need to convert a number into an unsigned byte. The number is always less than or equal to 255, and so it will fit in one byte.
我还需要将该字节转换回该数字.我将如何在 Java 中做到这一点?我已经尝试了几种方法,但都没有奏效.这是我现在要做的:
I also need to convert that byte back into that number. How would I do that in Java? I've tried several ways and none work. Here's what I'm trying to do now:
int size = 5;
// Convert size int to binary
String sizeStr = Integer.toString(size);
byte binaryByte = Byte.valueOf(sizeStr);
现在将该字节转换回数字:
and now to convert that byte back into the number:
Byte test = new Byte(binaryByte);
int msgSize = test.intValue();
显然,这不起作用.由于某种原因,它总是将数字转换为 65.有什么建议吗?
Clearly, this does not work. For some reason, it always converts the number into 65. Any suggestions?
推荐答案
一个字节总是用 Java 签名的.不过,您可以通过将其与 0xFF 进行二进制与运算来获得其无符号值:
A byte is always signed in Java. You may get its unsigned value by binary-anding it with 0xFF, though:
int i = 234;
byte b = (byte) i;
System.out.println(b); // -22
int i2 = b & 0xFF;
System.out.println(i2); // 234
这篇关于如何将 Int 转换为无符号字节并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 Int 转换为无符号字节并返回
基础教程推荐
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
