2013-10-14 37 views
0

我在C程序設計新和我測試一些代碼,我接收和處理格式化爲後續一個UDP包:C UINT16如何正確使用?

UINT16 port1 
UINT16 port2 

在這個測試的相應的值是:

6005 
5555 

如果我打印整個數據包緩衝區我得到的是這樣的:

u^W³^U><9e>^D

所以我想,我只想必須將其分解並處理爲16字節的unsigned int。所以我試過這樣的事情:

int l = 0; 
unsigned int *primaryPort = *(unsigned int) &buffer[l]; 
AddToLog(logInfo, "PrimaryPort: %u\n", primaryPort); 
l += sizeof(primaryPort); 
unsigned int *secondaryPort = *(unsigned int) &buffer[l]; 
AddToLog(logInfo, "SecondaryPort: %u\n", secondaryPort); 
l += sizeof(secondaryPort); 

但我得到8位數字的錯誤數字。

我甚至嘗試了另一種方法,如跟隨,但也得到了錯誤的數字。

int l = 0; 
unsigned char primaryPort[16]; 
snprintf(primaryPort, sizeof(primaryPort), "%u", &buffer[l]); 
AddToLog(logInfo, "PrimaryPort: %d\n", primaryPort); 
l += sizeof(primaryPort); 
unsigned char secondaryPort[16]; 
snprintf(secondaryPort, sizeof(secondaryPort), "%u", &buffer[l]); 
AddToLog(logInfo, "SecondaryPort: %d\n", secondaryPort); 
l += sizeof(secondaryPort); 

我在做什麼錯?另外,爲什麼我必須釋放一個字符串變量,但我不需要釋放int變量?

+2

如果您問的是C,爲什麼C++和C#中的標籤? – n0rd

+1

最有可能的是,在你的系統中'unsigned int'實際上不是一個16位整數,而'sizeof(unsigned int)!= 2'。並且'*(unsigned int)&buffer [l]'沒有任何意義(也不能編譯):你正在投射一個指向一個整數的指針,然後試圖解引用這個整數。 –

+1

「另外,爲什麼我必須釋放char字符串變量,但是我不需要釋放int變量?」無論你是否需要調用'free',都不是變量類型的問題。 –

回答

0

要傳遞到AddToLogsnprintf指針指向整數。所以你看到的是整數的地址,而不是整數本身。

您需要取消引用您的指針 - 例如,在您的第一種方法中,在primaryPort之前在號碼AddToLog的前面加上星號(*)。

正如@rileyberton所示,最有可能的是unsigned int是4字節在您的系統上,這是C99類型uint32_t。對於16位整數,請使用uint16_t。這些在stdint.h中定義。這些都是傳統上被稱爲「短整型」或「半整數」,並要求在printf或類似功能的%hu預選賽,而不僅僅是%u(代表unsigned int,其大小取決於在目標機器上。)

而且, @ igor-tandetnik認爲,如果例如數據包使用網絡順序(big-endian)格式,並且目標機器使用的是小端格式,則可能需要切換數據包中整數的字節順序。

0

系統上的unsigned int可能是4個字節(uint32_t)。如果你用正確的字節數掩蓋了值,或者簡單地使用short,你可以在這裏使用unsigned int。

int l = 0; 
unsigned short *primaryPort = *(unsigned short) &buffer[l]; 
AddToLog(logInfo, "PrimaryPort: %u\n", primaryPort); 
l += sizeof(*primaryPort); 
unsigned short *secondaryPort = *(unsigned short) &buffer[l]; 
AddToLog(logInfo, "SecondaryPort: %u\n", secondaryPort); 
l += sizeof(*secondaryPort); 
+1

或..你知道..'uint16_t'。 – Thomas

0

您聲明primaryPortsecondaryPort是指向unsigned short的指針。

但是,當您從一部分緩衝區中爲它們賦值時,您已經取消了對指針的引用。你不需要pointers-to-unsigned-short。你只需要一個unsigned short

將其更改爲:

unsigned short primaryPort = *((unsigned short*) &buffer[l]); 

unsigned short secondaryPort = *((unsigned short *) &buffer[l]); 

注意在變量聲明中移除*的。

如果仍然有問題,則需要檢查buffer逐字節,查找您期望的值。您可以預期6005將顯示爲十六進制17 7575 17,具體取決於您的平臺的endianness