1:判断大端小端机器方法
inti=0X12345678
0X120X340X560X78 大端存储(BigEndian)按照字符串从左向右的顺序存储
0X78 0X560X340X12小端存储(LittleEndian)
程序:
利用联合类型,联合类型,个联合共享一段内存空间,一个联合变量的长度是各成员中最长的长度
int main() { union ut{ short s; char c[2]; }u; if(sizeof(short) == 2) { u.s = 0x0102; if(u.c[0] == 1 && u.c[1] == 2) { printf("big enidan/n"); }else if(u.c[0] == 2 && u.c[1] == 1) { printf("little endian./n"); } return 0; } }
2:java 内存中数据的存储 采用的是大端模式
而C++是 采用 小端模式
服务器端是c++ 客户端是java 这样发送数据的时候 字节顺序要进行调整,因为C++server端直接从socket流中读取出数据,没有关心是否将数据按照网络字节顺序(即大端模式)进行解析
则:
如果发送int类型的数据时候 ,就需要手动组拼 字节数组,将int转换为字节数组
/**
* 将int转为低字节在前,高字节在后的byte数组 */
private static byte[] toLH(int n) {
byte[] b = new byte[4];
b[0] = (byte) (n & 0xff);
b[1] = (byte) (n >> 8 & 0xff);
b[2] = (byte) (n >> 16 & 0xff);
b[3] = (byte) (n >> 24 & 0xff);
return b;
}
同样其它类型的数据(除字符型外)也需要进行字节顺序调整
问题2:如果C++服务器接受字符使用的是wchar_t字节 类型 那java传递字符类型的时候要注意
调整字节顺序, 因为wchar_t类型 针对汉字和英文都占用两个字节
例子: String name = "杨abc";
上面的字符串其 大端显示情况为:
public static void printbyte(byte[] bt)
{
for (int i = 0; i < bt.length; i++){
int hex = (int)bt[i] & 0xff;
System.out.print(Integer.toHexString(hex) + " ");
}
System.out.println(" length = "+bt.length);
}
@Test
public void test1() throws UnsupportedEncodingException {
String name = "杨彬abc";
// TODO Auto-generated method stub
byte[] defaultBytes = name.getBytes();
printbyte(defaultBytes);
byte[] utf_8 = name.getBytes("utf-8");
printbyte(utf_8);
byte[] utf_16be = name.getBytes("utf-16be");
printbyte(utf_16be);
byte[] utf_16le = name.getBytes("utf-16le");
printbyte(utf_16le);
byte[] gbk = name.getBytes("gbk");
printbyte(gbk);
/*
*
e6 9d a8 e5 bd ac 61 62 63 length = 9 默认
e6 9d a8 e5 bd ac 61 62 63 length = 9 utf-8 汉字占三个字节
而utf-8 采用 3 个字节存储汉字 1个字节存储英文字符
unicode 采用两个字节存储汉字及英文字符
67 68 5f 6c 0 61 0 62 0 63 length = 10 大端方式 汉字占两个字节
68 67 6c 5f 61 0 62 0 63 0 length = 10 小端方式
gbk采用两个字节存储汉字
d1 ee b1 f2 61 62 63 length = 7
*/
//网络编程socket 通讯 针对字符串采用 utf-16le 这种方式存储
}