2016-05-29 47 views
-1

我想將字符數組轉換爲數組,其中每個字符被分成兩個半字節,然後放回到另一個數組中。如何將緩衝區(字節數組)更改爲C中充滿半字節的數組?

事情是這樣的:

Buffer[2] = {{10110101},{10100101}} 

nibbleArray[4] = {{00001011},{00000101},{00001010},{00000101}} 

但我想不出哪裏開始。有任何想法嗎?

+1

將目標數組定義爲源數組的兩倍。然後循環並做數學。 – alk

+2

'000010101'?這不可能是正確的 – harold

+1

你*可以*在這裏使用位置提示,但這可以通過簡單地應用在學校學到的適當的算術運算(+, - ,*,/)來解決...... - 好的,在整數域。 – alk

回答

1

您可以使用位操作從字節中提取半字節。越來越低半字節:

char nibble = byte & 0x0F; 

越來越高半字節:

char nibble = (byte & 0xF0) >> 4; 

&位操作者執行邏輯與位之間。 0x0F0b00001111,所以&與它只會保留在低半字節的位。

同樣,0xF00b11110000二進制,所以&與它只會保持較高的半字節位設置。但是,這會將字節0b10110101轉換爲0b10110000,這不是您想要的。這些位需要右移(4),使其成爲0b00001011。這由>>運營商完成。

+0

'&0xF0'不是必需的,移位拋出這些位無論如何 – harold

+0

@harold這是真的,只要你有輸入字節(字符)。但它表達了代碼的目的,所以我可能會將它保留在那裏。足夠智能的編譯器甚至可以優化它。 –

0

的一種方法使用純數學:

#include <errno.h> 


int byte2nibbles(int byte, int * phn, int * pln) 
{ 
    int result = 0; 

    if (((0xff >= byte) && (0 <= byte)) && ((NULL != phn && NULL != pln))) 
    { 
    (*phn) = byte/0x10; 
    (*pln) = byte - ((*phn) * 0x10); 
    } 
    else 
    { 
    errno = EINVAL; 
    result = -1; 
    } 

    return result; 
} 

使用方法如下:

#include <stdio.h> 

int byte2nibbles(int, int *, int *); 


int main(void) 
{ 
    unsigned char byte = 0xAB; 
    int nibble_higher, nibble_lower; 

    if (-1 == byte2nibbles(byte, &nibble_higher, &nibble_lower)) 
    { 
    perror("byte2nibble() failed"); 
    return EXIT_FAILURE; 
    } 

    printf("byte = 0x%02hhx, higher nibble = 0x%02hhx, lower nibble = 0x%02hhx\n", 
    byte, nibble_higher, nibble_lower); 

    return EXIT_SUCCESS; 
} 

輸出是:

byte = 0xab, higher nibble = 0x0a, lower nibble = 0x0b 
0

下面是使用位擺弄一個完整的例子 - 位字段

#include<stdio.h> 

typedef struct nibble{ 
char hh : 4; //hh - higher half. See 2 for what is a bit field? 
char lh : 4; //lh - lower half 
}nibble; 
int main(void) 
{ 
int i=0; 
unsigned char b[2]={'A','b'}; //See [1] for why unsigned? 
nibble obj[2]; 
while (i<2){ 
chartonibble(b[i],&obj[i]); 
i++; 
} 
i=0; 
while (i<2){ 
printf("obj[%d] higher half : %d\n",i,obj[i].hh); 
printf("obj[%d] lower half : %d\n",i,obj[i].lh); 
i++; 
} 
return 0; 
} 

void chartonibble(unsigned char c, nibble* ptr){ 
    ptr->hh=(c >> 4); 
    ptr->lh=(c & 0x0f); 
    } 

參考文獻:

  1. [ Right Shift ]操作。
  2. C [ Bit-Fields ]