1. 程式人生 > >整型變數(int)與位元組陣列(byte[])的相互轉換

整型變數(int)與位元組陣列(byte[])的相互轉換

// int2byte.cpp : 定義控制檯應用程式的入口點。
//

#include "stdafx.h"
#include <Windows.h>

/*
#define MAKEWORD(a, b)	((WORD)(((BYTE)(((DWORD_PTR)(a)) & 0xff)) | ((WORD)((BYTE)(((DWORD_PTR)(b)) & 0xff))) << 8))
#define MAKELONG(a, b)	((LONG)(((WORD)(((DWORD_PTR)(a)) & 0xffff)) | ((DWORD)((WORD)(((DWORD_PTR)(b)) & 0xffff))) << 16))
#define LOWORD(l)		((WORD)(((DWORD_PTR)(l)) & 0xffff))
#define HIWORD(l)		((WORD)((((DWORD_PTR)(l)) >> 16) & 0xffff))
#define LOBYTE(w)		((BYTE)(((DWORD_PTR)(w)) & 0xff))
#define HIBYTE(w)		((BYTE)((((DWORD_PTR)(w)) >> 8) & 0xff))
*/

// ==========================================================
//   Big Endian / Small Endian utility functions
// ==========================================================
BOOL IsSmallEndian()
{
	DWORD wd = 0x22; 
	if( *((BYTE *)&wd) == 0x22 )  // Small Endian
		return TRUE;
	else
		return FALSE;
}

void SwapShort(WORD *sp) {
		BYTE *cp = (BYTE *)sp, t = cp[0]; cp[0] = cp[1]; cp[1] = t;
}

void SwapLong(DWORD *lp) {
		BYTE *cp = (BYTE *)lp, t = cp[0]; cp[0] = cp[3]; cp[3] = t;
		t = cp[1]; cp[1] = cp[2]; cp[2] = t;
}

// int 2 byte
BYTE *Int2Byte(int nVal)
{
	BYTE *pByte = new BYTE[4];
	for (int i = 0; i<4;i++)
	{
		pByte[i] = (BYTE)(nVal >> 8*(3-i) & 0xff);
	}
	return pByte;
}

// byte 2 int
int Byte2Int(BYTE *pb)
{
	// assume the length of pb is 4
	int nValue=0;
	for(int i=0;i < 4; i++)
	{
		nValue += ( pb[i] & 0xFF)<<(8*(3-i));
	}
	return nValue;
}

int _tmain(int argc, _TCHAR* argv[])
{
	//PC, 小端位元組

	//////////////////////////////////////////////////////////////////////////
	BYTE *byte = Int2Byte(0x12345678);
	printf("byte[0]=0x%xh,byte[1]=0x%xh,byte[2]=0x%xh, byte[3]=0x%xh\n", byte[0], byte[1], byte[2],byte[3]);

	int nVal = Byte2Int(byte);
	printf("nVal=0x%xh\n\n",nVal);



	//////////////////////////////////////////////////////////////////////////
	// 小端位元組應該是得到 0xefcdab89, 大端得到0x89abcdef
	WORD wLow, wHigh;
	DWORD dwData;

	BYTE b[4] = {0x89, 0xab, 0xcd, 0xef};
	DWORD dwVal = 0xefcdab89;

	// DWORD分解成BYTE陣列
	WORD lo = LOWORD(dwVal),
		hi = HIWORD(dwVal);

	printf("lo=0x%xh,hi=0x%xh\n", lo, hi);

	//BYTE陣列組合成DWORD
	wLow = MAKEWORD(b[0],b[1]);
	wHigh = MAKEWORD(b[2], b[3]);
	dwData = MAKELONG(wLow, wHigh);
	printf("wLow=0x%xh,wHigh=0x%xh,dwData=0x%xh\n", wLow, wHigh, dwData);

	getchar();
	return 0;
}