2011-11-10 59 views
3

如果我想位5由3整數移位,所以int a = 5; int b = a << 3;,其結果將是40十進制作爲510140101000位位移char數組

如果不過,我有以下char陣列: 00000 00101和比特移位三到左邊,我想要的結果是00001 01000。所以我想要適應0的填充。你有什麼建議?

回答

3

如果你的意思是一個實際的char數組,你可以使用memmove()memset()

char str[] = "0000000101"; 

int shift = 3; 
int length = strlen(str); 

memmove(str, str + shift,length - shift); 
memset(str + length - shift,'0',shift); 

// Result: 
// "0000101000" 
+0

你正在向右移動,而不是向左移動,並且溢出了數組,因爲你'memmove()''length'字節,而不是'length - shift'。 – Dave

+0

謝謝,我看到您的第一條評論,並將其修復了幾分鐘。前。編輯:我正在向左轉。我測試過了。 – Mysticial

+0

是的,我在智慧上翻轉了'src'和'dst'的順序。您當前的代碼是正確的。 – Dave

1

訪問緩衝區16位的指針,使用htons取尾數的保健問題

char c[2] = {0, 5}; 

uint16_t* p16 = (uint16_t*)c; 

*p16 = htons((ntohs(*p16) << 3));