C#到Java byte类型冲突的解决

最近要改写一个核心加密认证类,从C#改写成Java。

发现在调试时,加密的数据无论如何也对不上。

经过跟踪,发现问题出在C#和Java byte类型的区别上:在C#里 byte类型是无符号的,而Java里是有符号的,所以C#里的129到Java里就成了负数。

发现了问题,解决就比较容易了,针对Java的byte,采用Int来进行存储。

通过如下代码从byte到int进行转换:

[java]  view plain copy
  1. /** 
  2.  * from byte to int, because of byte in java is signed 
  3.  */  
  4. private static int toInt(int b) {  
  5.     return b >= 0 ? (int)b : (int)(b + 256);  
  6. }  

对于下面C#的代码:

[c-sharp]  view plain copy
  1. private static AuthenticationTicket FromByteArray(byte[] buf)  
  2. {  
  3.     MemoryStream ms = new MemoryStream(buf);  
  4.     BinaryReader reader = new BinaryReader(ms);  
  5.   
  6.     short version = reader.ReadInt16();  
  7.     short scope = reader.ReadInt16();  
  8.     int key = reader.ReadInt32();  
  9. }  

改写为如下形式,相当于重新实现BinaryReader的ReadInt16和ReadInt32方法。

[java]  view plain copy
  1. private static AuthenticationTicket FromByteArray(int[] bufInt)  
  2. {             
  3.     int version = readInt16(bufInt);  
  4.     int scope = readInt16(bufInt);  
  5.     long key = readInt32(bufInt);     
  6. }  
  7.    
  8.  private static int readInt16(int[] bufInt) {  
  9.      int i = 0;   
  10.      for(int j = 0; j < 2; readArrayIndex++, j++) {  
  11.             i += bufInt[readArrayIndex] << (j << 3);  
  12.      }  
  13.      return i;  
  14.  }  
  15.   
  16.  private static long readInt32(int[] bufInt) {  
  17.      long i = 0;   
  18.      for(int j = 0; j < 4; readArrayIndex++, j++) {  
  19.             i += bufInt[readArrayIndex] << (j << 3);  
  20.      }  
  21.      return i;  
  22.  }  

上面的例子说明,c#和Java虽然非常相像,但是一些关键细节的不同是需要仔细考虑的。


原文地址:http://blog.csdn.net/hfahe/article/details/5580034

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值