2012年2月1日 星期三

【C語言】一堆子轉換函式

許多初學者而言,資料的轉換仍然是一個問題,在此整理一些函式說明如下:

大概分為三類
  1. 字串與數值轉換
  2. 位元順序轉換
  3. 網路位址轉換

字串與數值轉換
    常見的就是atoi(),atol(),atof(),itoa() ... 之類的,其中itoa() 不被gcc所支援,可透過sprintf()來實現轉換,並僅以atoi()與sprintf()為例
  
原型宣告使用方法使用時機
#include 
int atoi (const char *str);
int a;
a=atoi("100");
將數值字串轉換成整數
#include 
int sprintf (char *str,const char *format,...);
char s[10];
sprintf(s,"%s",100);
將數值轉換為字串


位元順序轉換
    位元序序轉換是因為x86 cpu讀取記憶體的順序與磁碟上存放的順序不同而造成的,x86架構是所謂的Little-Endian,在磁碟上儲存的位元組是照順序的,然而以32位元記憶體存取而言,會先從低位元開始讀取,例如…在磁碟上存放的資料是0x12345678,那麼讀進記憶體之後,就會是0x78 0x56 0x34 0x12
所以,從在儲存媒體與記憶體之間的資料需要轉換。另外就是用於Host Byte Order 與 Network Byte Order 互換,因為網路跨平台的特性,無論主機端是Big-Endian 或是Little-Endian 都要能正確地透過網路交換資料,所以在Socket定義上,Network Byte Order 採用 Big-Endian 。以下函式可達成轉換:
#include 

uint32_t htonl(uint32_t hostlong);//32位元資料轉換
uint16_t htons(uint16_t hostshort);//16位元資料轉換
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

僅以host 中32位元記憶體中資料 0x78563412 為例:
原型宣告使用方法使用時機
#include 
uint32_t htonl(uint32_t hostlong);
unsigned int a,b;
a=0x78563412;
b=htonl(a);
1.host轉換成network 順序
2.memory 資料寫入磁碟的轉換
(0x78563412-->0x12345678)
#include 
uint32_t ntohl(uint32_t netlong);
unsigned int a,b;
b=0x12345678;
a=ntohl(b);
1.network 轉換成host順序(0x12345678-->0x12345678)

網路位址轉換 
    網路位址轉換是32位元IP值與IP字串的轉換,例如我們所輸入的IP 192.168.100.111 是一組字串,但是socket api 接受的是32位元IP值,所以需要轉換,或是從socket api 取得的32位元IP值,要轉換成可顯示的字串格式,可例用下列函式:
#include 
#include 
#include 

char *inet_ntoa(struct in_addr in);
int inet_aton(const char *cp, struct in_addr *inp);
in_addr_t inet_addr(const char *cp);

原型宣告使用方法使用時機
#include 
#include 
#include  
char *inet_ntoa(struct in_addr in); 
char ipbuf[16];
struct in_addr addr;
addr.s_addr =0xC0A86401;
sprintf(ipbuf,"%s",inet_ntoa(addr));
32位元IP Address 轉換為IP字串

            
#include 
#include 
#include 
int inet_aton(const char *cp, \ struct in_addr *inp);
struct in_addr addr;
unsigned int ip;
ip=inet_aton("192.168.100,1",&addr);
IP字串轉換為32位元IP Address

沒有留言:

張貼留言

How to use simple speedtest in RaspberryPi CLI

  pi@ChunchaiRPI2:/tmp $  wget -O speedtest-cli https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py --2023-06-26 10:4...