从整数创建一个字节 [英] Creating a byte from an integer

查看:139
本文介绍了从整数创建一个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用整数创建一个字节。例如,我有一个4的整数,我想创建一个值为4的字节。当我做的事情像

I want to create a byte using an integer. For example I have an integer of 4, I want to create a byte with a value of 4. When I do something like

byte test = 134;

我得到的字节值为-122,我希望字节值只有134,这样我才能稍后将此转换为ascii。

I get an byte value of -122 wheras I want a byte value of simply 134 so that i can convert this to ascii later on.

我不确定如何实现此目的,但欢迎任何可以提供的帮助。谢谢。

I am unsure of how to achieve this but would welcome any help that can be provided. Thanks.

推荐答案

在Java byte 中被解释为签名(沿着 int s, short s, long s) 。 134 的无符号字节值与 -122 的有符号字节值相当。如果您希望使用 byte 的无符号值,可以将此值存储在超过8位的有符号整数中,例如 int

In Java bytes are interpreted as signed (along with ints, shorts, and longs). The unsigned byte value of 134 is bit-equivalent to the signed byte value of -122. If you wish to use the unsigned value of a byte, you can do so by storing this value in a signed integer with more than 8 bits, such as an int:

byte test = (byte) 134;
int unsignedByteValue = ((int) test) & 0xff;
// now unsignedByteValue == 134

0xff的位掩码确保只有 unsignedByteValue 的低8位为1。否则,负签名的字节将导致签名扩展名为负$ signed c $ c> int 。

The bitmask of 0xff ensures that only the lower 8 bits of unsignedByteValue are ones. Otherwise, a negative signed byte would result in a negative signed int by sign extension.

这篇关于从整数创建一个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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