2011-08-19 35 views
0

我有一個隨機值(稱爲頭)8個採樣和我有十六進制值命令,參見下文:如何從java或c中的8位樣本中創建1個字節?

[8 bit][command] 
\  | 
    \  \------------------ [01 30 00 00 = hex start the machine] 
    \ 
    +-------------------+ 
    | 00001111 = hi  | 
    | 00000000 = hello | 
    | 00000101 = wassup | 
    +-------------------+ 

你怎麼了8個採樣轉換爲1個字節,並與上述六角加入吧價值?

+1

什麼是你樣本的格式?我的意思是你使用哪種數據結構,並且想要以什麼格式傳遞8位樣本和命令,將其轉換爲1個單個字節 – Snicolas

+0

? – xitx

+1

@Snicolas:示例格式顯示在8位以上,如00001111.(通過RS232或TCP的結果是ASCII或二進制) – YumYumYum

回答

2

在這兩種語言中,您都可以使用bitwise operations

所以在C,如果您有:

uint32_t command; 
uint8_t sample; 

您可以連接到這些如64位數據類型如下:

uint64_t output = (uint64_t)command << 32 
       | (uint64_t)sample; 

如果你不是要輸出字節數組(序列化通過RS-232或其他),那麼你可以這樣做:

uint8_t output[5]; 
output[0] = sample; 
output[1] = (uint8_t)(command >> 0); 
output[2] = (uint8_t)(command >> 8); 
output[3] = (uint8_t)(command >> 16); 
output[4] = (uint8_t)(command >> 32); 
相關問題