2015-03-19 624 views
0

我正在製作一個程序來與串行設備進行通信。設備以十六進制格式向我提供數據。我得到的十六進制格式是FFFFFF84,但我有興趣提取最後兩位,即84。那麼我如何提取它?如何從十六進制值中提取低位字節?

while(1) 
{ 
int i; 
char receivebuffer [1]; 
read (fd, receivebuffer, sizeof receivebuffer); 
for (i = 0; i < sizeof (receivebuffer); i++) 
{ 
    printf("value of buffer is %X\n\n", (char)receivebuffer[i]); 

} 
return 0; 
} 

我正在接收receivebuffer中的數據。請幫忙謝謝。

回答

1

你,因爲printf正在打印您的數據,只是困惑的符號擴展int(這意味着你的系統charchar被視爲簽字 - 注意,這是實現定義)。

更改printf到:

printf("value of buffer is %#X\n\n", (unsigned char)receivebuffer[i]); 

或只是把類型receivebuffer無符號:

unsigned char receivebuffer[1]; 

// ... 

printf("value of buffer is %#X\n\n", receivebuffer[i]); 
0

設備只是返回字節。它是printf,它以某種格式顯示一個字節(十進制,十六進制等)。要以十六進制顯示字節,您應該使用「0x%02x」格式。

1

設備以十六進制格式給我提供數據。

這與您的代碼相矛盾。看起來設備爲您提供二進制(原始)格式的數據,並將其轉換爲十六進制打印。這是一個巨大的差異。

如果你

printf("value of buffer is %X\n\n", (char)receivebuffer[i]); 

char(其轉換是不必要的,因爲它已經是一個char)被轉換爲int。由於您的系統已簽署char,因此產生的int爲負值,因此開始時爲FFF...

你可以做任何的

printf("value of buffer is %X\n\n", receivebuffer[i] & 0xFF); 
printf("value of buffer is %X\n\n", (unsigned char)receivebuffer[i]); 
printf("value of buffer is %X\n\n", (uint8_t)receivebuffer[i]); 
0
要提取的最後2個字節

?你需要操作者 '&' 解壓:

FFFFFF84 -> 1111 1111 1111 1111 1111 1111 1000 0100 
000000FF -> 0000 0000 0000 0000 0000 0000 1111 1111 
--------------------------------------------------- 
after & -> 0000 0000 0000 0000 0000 0000 1000 0100 

所以anwser是做任務:

last2 = input & 0xFF 

希望這anwser幫助您瞭解位操作。

相關問題