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虽然非常相像,但是一些关键细节的不同是需要仔细考虑的。
相关文档:
import java.util.LinkedList;
import java.util.List;
public class ShortestPaths {
private static String showPath[] = { "", "", "", "", "", "" };
& ......
最近因为在做金融项目,里面对byte的操作要求比较多,所以在这里整理了一下关于Java中的byte类型。
Java虚拟机中没有byte类型
恩。。。怎么说呢,个人感觉这个说法有点儿唬人的意思。的确,当这个想法刚刚出现在我的脑海中的时候我觉得也有些胡扯,毕竟byte类型就在那里,怎么能说Java虚拟机中没有byte类型呢?
好吧, ......
关于java的http协议文件上传实用例题一
(2006-07-25 16:43:56)
转载
分类:
java
关于java的http协议上传:(简单实用而且健壮;速度快)
此方法比apache的文件上传包(uploadfile1.1:就文件上传功能而言)要强多了
1.只需要一个MultipartRequest.java基本文件就行。
2.前台html的基本格式
<html ......
使用Runtime.getRuntime().exec()方法可以在java程序里运行外部程序.
该方法有6个可访问版本:
1.exec(String command)
2.exec(String command, String envp[], File dir)
3.exec(String cmd, &n ......
在SUN推出 LWUIT开发包之前,在Java ME平台上开发用户界面并不是一件容易的事,尤其是想做出很眩的界面,更是难上加难,这是因为由MIDP本身提供的用户界面元素,包javax.microedition.lcdui
中提供的组件功能相对简单。
使用 LWUIT 开发包,开发人员不再需要编写与设备屏幕大小相关的代码,它采用了与Swing 相似的概念提 ......