UVa 594 One Little, Two Little, Three Little Endians.
解題背景
這題是傳說中的Endian問題。我們都知道int占用4 bytes,但是很神奇的這 4 byte 在記憶體中的排列方式並不固定,分為兩派,一派是以 Intel 為首的 little-endian,另一派是網路傳輸使用的 big-endian。我用例子來說明,有個變數: int x = 11112345; 如果我們從記憶體的角度來看這個變數x,也就是轉換為二進位bit來觀察,那麼會看見以下兩種狀況:
變數 x 的四個 byte 在 big-endian 的機器上做如此排列
00000000 10101001 10001111 10011001
但是在 little-endian 的機器上,卻以這樣的方式儲存
10011001 10001111 10101001 00000000
兩者byte擺放的順序恰好相反,若一個不小心,就會解讀為完全錯誤的數值,因此 Endian 一直是計算機系統必須處理的問題,這兒有個連結談到Endians的歷史由來。本題就是要做 endian 轉換。
解題策略
C語言可以把 int 當作 char array 來操作,髒,但有效。int big, little; char * plittle = (char*) &little; char * pbig = (char*) &big; pbig[0] = plittle[3]; pbig[1] = plittle[2]; pbig[2] = plittle[1]; pbig[3] = plittle[0];
閒聊
感謝蔡神的大一計概。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* UVa 594 One Little, Two Little, Three Little Endians | |
* Author: chchwy | |
* Last Modified: 2011.03.29 | |
* Blog: http://chchwy.blogspot.com | |
*/ | |
#include<cstdio> | |
using namespace std; | |
int to_big(int little) | |
{ | |
char* p = (char*) &little; | |
swap(p[0], p[3]); | |
swap(p[1], p[2]); | |
return little; | |
} | |
int main() | |
{ | |
#ifndef ONLINE_JUDGE | |
freopen("594.in", "r", stdin); | |
#endif | |
int little = 0; | |
while (scanf("%d", &little) == 1) | |
{ | |
printf("%d converts to %d\n", little, to_big(little)); | |
} | |
return 0; | |
} |
留言
張貼留言