java 保存unsigned 数据方法

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.gif ExpandedBlockStart.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、付费专栏及课程。

余额充值