0
点赞
收藏
分享

微信扫一扫

判断CPU或JVM是大端还是小端的方法——字节数组与整形互转


----------字节数组转为整形

C版:

/**
 * Windows 7 32位,CodeBlocks
 */
#include <stdio.h>
#include <stdlib.h>

/**
 * 将字节数组(char[])转为整形(int)
 */
int main()
{
	char chArray[] = {0x78,0x56,0x34,0x12};
	int *p = (int *)chArray;
	printf("%x\n", *p);
	return 0;
}
// output: 12345678

结论:说明 CPU 是小端


Java版:

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

public class Test
{
	/**
	 * 将字节数组(byte[])转为整形(int)
	 */
	public static void main(String[] args) throws IOException
	{
		byte[] byteAr = new byte[4];
		byteAr[0] = 0x78;
		byteAr[1] = 0x56;
		byteAr[2] = 0x34;
		byteAr[3] = 0x12;
		ByteArrayInputStream bais = new ByteArrayInputStream(byteAr);
		DataInputStream dis = new DataInputStream(bais);
		System.out.println(Integer.toHexString(dis.readInt()));
	}
}
// output: 78563412

结论:说明 JVM 是大端


----------整形转为字节数组

C版:

#include <stdio.h>
/**
 * 将整形(int)转为字节数组(char[])
 */
int main()
{
	int a = 0x12345678;
	char *p = (char *)(&a);
	int i;
	for(i = 0; i < 4; i++)
	{
		printf("%x\n", p);
		printf("%x\n", *p);
		p++;
	}
}
/*
22ff44
78
22ff45
56
22ff46
34
22ff47
12
*/

结论:说明 CPU 是小端



Java版:

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class Test
{
	public static void main(String[] args) throws IOException
	{
		/**
		 * 将整形(int)转为字节数组(byte[])
		 */
		int a = 0x12345678;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);
		dos.writeInt(a);
		byte[] b = baos.toByteArray();
		for(int i = 3; i >= 0; i--)
		{
			System.out.print(Integer.toHexString(b[i]));
		}
		System.out.println();
	}
}
// Output: 78563412

结论:说明 JVM 是大端



----------关于大端与小端
All processors must be designated as either big endian or little endian. Intel's 80x86 processors and their clones are little endian. Sun's SPARC, Motorola's 68K, and the PowerPC families are all big endian. The Java Virtual Machine is big endian as well. 
摘自:http://www.eetimes.com/discussion/beginner-s-corner/4023889/Introduction-to-Endianness

一般PC都是小端储存
Java虚拟机使用big-endian, Intel x86使用 little-endian
摘自:http://www.eosfan.cn/forum.php?mod=viewthread&tid=5423

JVM采用了"big endian"的编码方式来处理这种情况,即高位bits存放在低字节中。这同 Motorola及其他的RISC CPU采用的编码方式是一致的,而与Intel采用的“little endian”的编码方式即低位bits存放在低位字节的方法不同。
摘自:http://www.hudong.com/wiki/JVM

writeInt()
Writes an int to the underlying output stream as four bytes, high byte first.
说明writeInt()也是按照big-endian的方式处理的
摘自:JDK文档



举报

相关推荐

0 条评论