怎么取各個位的值?
利用文件,你把這個數值用二進制的方法寫入文件,然后以char型讀取。
(運行環境:64位CentOS,sizeof(int)=4)
通過memcpy,將int型變量的首地址作為src buffer,char數組作為dst buffer,每個int型變量占據buffer的4個字節。
參考代碼如下:
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 10
int main(int argc, char * argv[]) {
char buffer[BUFFER_SIZE] = {0};
int input1 = 0, input2 = 0, output1 = 0, output2 = 0;
printf("size of int: %d\n", sizeof(int));
printf("Please input two integers\n");
scanf("%d", &input1);
scanf("%d", &input2);
printf("The input integers are : %d %d\n", input1, input2);
memcpy(buffer, &input1, sizeof(int));
memcpy(buffer + sizeof(int), &input2, sizeof(int));
printf("Buffer:\n");
for (int i = 0; i < BUFFER_SIZE; ++i) {
printf("0x%02x ", buffer[i]);
}
printf("\n");
memcpy(&output1, buffer, sizeof(int));
memcpy(&output2, buffer + sizeof(int), sizeof(int));
printf("The output integers retrieved from buffer: %d %d\n", output1, output2);
return 0;
}
注意:
不同語言、不同機器間通過buffer來存取int型值,要注意大頭、小頭的區別,必要時要做大小頭轉換操作