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

來源:互聯網
上載者:User

// 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 Endianreturn TRUE;elsereturn 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 byteBYTE *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 intint Byte2Int(BYTE *pb){// assume the length of pb is 4int 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, 大端得到0x89abcdefWORD 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數組組合成DWORDwLow = 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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.