java 保存unsigned 数据方法

本文介绍了在Java中如何处理无符号数,由于Java不直接支持无符号类型,需要使用特定的方法来读取和存储无符号数据。文章通过示例代码详细解释了如何从字节流中提取无符号字节、短整型和整型数据,并将其转换为Java可识别的类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java中没有unsiged的设置,必须用signed的数据存储,也就是要多用些存储空间。
use a short to hold an unsigned byte, use a long to hold an unsigned int.
use a char to hold an unsigned short.
('char' type, which is a 2 byte representation of unicode, instead of the
C 'char' type, which is 1 byte ASCII. Java's 'char' also can be used as
an unsigned short, i.e. it represents numbers from 0 up to 2^16.)
ContractedBlock.gifExpandedBlockStart.gif从字节流中提取unsigned 数据,保存unsigned数据到字节流
short anUnsignedByte = 0;
char anUnsignedShort = 0;
long anUnsignedInt = 0;

int firstByte = 0;
int secondByte = 0;
int thirdByte = 0;
int fourthByte = 0;

byte buf[] = getMeSomeData();
// Check to make sure we have enough bytes
if(buf.length < (1 + 2 + 4))
doSomeErrorHandling();
int index = 0;

firstByte
= (0x000000FF & ((int)buf[index]))
index
++;
anUnsignedByte
= (short)firstByte;

firstByte
= (0x000000FF & ((int)buf[index]))
secondByte
= (0x000000FF & ((int)buf[index+1]))
index
= index+2;
anUnsignedShort
= (char) (firstByte << 8 | secondByte);

firstByte
= (0x000000FF & ((int)buf[index]))
secondByte
= (0x000000FF & ((int)buf[index+1]))
thirdByte
= (0x000000FF & ((int)buf[index+2]))
fourthByte
= (0x000000FF & ((int)buf[index+3]))
index
= index+4;
anUnsignedInt
= ((long) (firstByte << 24
| secondByte << 16
| thirdByte << 8
| fourthByte))
& 0xFFFFFFFFL;
// write it back as unsigned int, unsigned short, unsigned byte.
buf[0] = (anUnsignedInt & 0xFF000000L) >> 24;
buf[
1] = (anUnsignedInt & 0x00FF0000L) >> 16;
buf[
2] = (anUnsignedInt & 0x0000FF00L) >> 8;
buf[
3] = (anUnsignedInt & 0x000000FFL);

buf[
4] = (anUnsignedShort & 0xFF00) >> 8;
buf[
5] = (anUnsignedShort & 0x00FF);

buf[
6] = (anUnsignedByte & 0xFF);

转载于:https://www.cnblogs.com/clarkchen/archive/2011/05/22/2053459.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值