C#到Java byte类型冲突的解决
最近要改写一个核心加密认证类,从C#改写成Java。
发现在调试时,加密的数据无论如何也对不上。
经过跟踪,发现问题出在C#和Java byte类型的区别上:在C#里 byte类型是无符号的,而Java里是有符号的,所以C#里的129到Java里就成了负数。
发现了问题,解决就比较容易了,针对Java的byte,采用Int来进行存储。
通过如下代码从byte到int进行转换:
/**
* from byte to int, because of byte in java is signed
*/
private static int toInt(int b) {
return b >= 0 ? (int)b : (int)(b + 256);
}
对于下面C#的代码:
private static AuthenticationTicket fromByteArray(byte[] buf)
{
MemoryStream ms = new MemoryStream(buf);
BinaryReader reader = new BinaryReader(ms);
short version = reader.ReadInt16();
short scope = reader.ReadInt16();
int key = reader.ReadInt32();
}
改写为如下形式,相当于重新实现BinaryReader的ReadInt16和ReadInt32方法。
private static AuthenticationTicket fromByteArray(int[] bufInt)
{
int version = readInt16(bufInt);
int scope = readInt16(bufInt);
long key = readInt32(bufInt);
}
private static int readInt16(int[] bufInt) {
int i = 0;
for(int j = 0; j < 2; readArrayIndex++, j++) {
i += bufInt[readArrayIndex] << (j << 3);
}
return i;
}
private static long readInt32(int[] bufInt) {
long i = 0;
for(int j = 0; j < 4; readArrayIndex++, j++) {
i += bufInt[readArrayIndex] << (j << 3);
}
return i;
}
上面的例子说明,c#和Java虽然非常相像,但是一些关键细节的不同是需要仔细考虑的。
相关文档:
关于 Java Concurrency
自从Java诞生之时,Java 就支持并行的概念,比如线程和锁机制。这个教程帮助开发多线程Java程序员能够理解核心的Java并行理念以及如何使用他们。 内容涉及到Java语言中的线程, 重练级以及轻量级同步机制 以及JavaSE 5 中的锁,原子量 并行容器,线程调度 以及线程执行者 ......
数字的格式化
DecimalFormat df = new DecimalFormat(",###.00");
double aNumber = 33665448856.6568975;
String result = df.format(aNumber);
Sytem. out.println(result);
输出结果为:
33,665,448,856.66
分析字符串
StringTokenizer(String s) 构造一 ......
Java语言的26个细节[转载]
Java作为一门优秀的面向对象的程序设计语言,正在被越来越多的人使用。本文试图列出作者在实际开发中碰到的一些Java语言的容易被人忽视的细节,希望能给正在学习Java语言的人有所帮助。
1,位移运算越界怎么处理
考察下面的代码输出结果是多少?
int a=5;
......
使用Runtime.getRuntime().exec()方法可以在java程序里运行外部程序.
该方法有6个可访问版本:
1.exec(String command)
2.exec(String command, String envp[], File dir)
3.exec(String cmd, &n ......