晓风残月
新手上路
posts - 6,comments - 49,trackbacks - 0

新手上路,最好的见面礼莫过于资源分享了。

毕业设计中关键技术是数据压缩模块,数据传输的是字节数组,却没有发现Java库中现成的整型于字节数组的转换,虽然Integer包装类有toBinaryString()之类的静态方法使用,但是却无法直接满足要求一个整数与4个字节数组的对应,幸好String类有getBytes()几个重载方法使用,要不然真的就哭死了

记得net中就有BinConverter可以直接使用,而且实现了bytes与int16,int32,char等等多类型的转换,有点感慨,还是.net方便,呵呵

也许是偶还没有发现相关的Java库,google得也不深入,没办法,时间不等人,只好自己实现了一个,经测试,正负数都OK(PS:google到一个算法,比较搞笑,只有负数是正确

 1 public   class  BitConverter  {
 2     
 3      public   static   byte [] getBytes( int  value)
 4     
 5          byte [] bytes  =   new   byte [ 4 ];
 6         bytes[ 0 = ( byte )( value  >>   24  );
 7         bytes[ 1 = ( byte )( (value  <<   8 >>   24  );
 8         bytes[ 2 = ( byte )( (value  <<   16 >>   24  );
 9         bytes[ 3 = ( byte )( (value  <<   24 >>   24  );        
10          return  bytes;            
11     }
         
12
13      public   static   int  toInt( byte [] bytes,  int  startIndex) {        
14          int  value  =   0 ;
15          for  ( int  j = startIndex;j < 4 ;j ++ {            
16             value  =  (value  <<   8 |  (bytes[j]  &   0xFF );
17         }
        
18          return  value;    
19     }

20 }

只有int版本,有时间了再研究其他数据类型的了。

欢迎大家抛砖,期待更加便捷的算法。
posted on 2006-05-19 04:43 jinglecat 阅读(1276) 评论(3)  编辑  收藏 所属分类: Java Prime

FeedBack:
# re: int to bytes to int
# re: int to bytes to int
2006-05-20 14:15 | jinglecat
@Dedian
thx so much!the url is appreciated.
it's algorithm for "int to bytes" seems simpler than mine.
it's a pity that it does not provider the implement of "int, float ... to bytes".
Do others have any ideas?  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: