2011-08-19 91 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); 
相关问题