如何将Int转换为无符号字节和后退 [英] How to Convert Int to Unsigned Byte and Back

查看:233
本文介绍了如何将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转换为无符号字节和后退的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆