バイト列の任意の位置から32ビット読み込んでint型として扱う
TCPやUDPなどのネットワークプログラムを書いてると、受信したバイト列の任意の位置から32ビットを読み込んでint型として扱いたくなる時がある。
例えば、受信したバイト列に整数「123」が含まれているとする。
整数「123」はバイト列に直すと
00 00 00 7b
となる。実際には、バイト列には他のデータも含まれているので
00 00 00 64 00 00 00 7b 00 00 04 d2
みたいな感じになる(「00 00 00 7b」以外は適当)。
このバイト列から4バイト(00 00 00 7b)をうまく切り出してint型にキャストすると整数「123」を復元することができる。
c言語で書くとこんな感じ
#include <stdio.h> typedef unsigend char UINT8; typedef unsigned int UINT32; UINT32 readUint32(UINT8 *bytes, int index){ return (UINT32)((UINT32)(bytes[index] << 0) | ((UINT32)bytes[index + 1] << 8) | ((UINT32)bytes[index + 2] << 16) | ((UINT32)bytes[index + 3] << 24)); } int main(void){ UINT8 bytes[] ={0xd2m 0x04, 0x00, 0x00, 0x7b, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00}; UINT32 temp; int *intVal; temp = readUint32(bytes, 4); intVal = (int *)&temp; printf("%d\n", *intVal); return 0; }