2016-01-22 26 views
1

我想將一個unsigned int值複製到char [2]變量中。我認爲複製是直截了當的,因爲它們都具有相同的大小(16位)。這裏是我的代碼:C中變量之間的複製

#include <stdlib.h> 
#include <stdio.h> 
int main() 
{ 
    unsigned short a = 63488; //16 bit value which is 1111100000000000; 
    unsigned char* b = malloc(2); 
    *b = a; 
    printf("%d\n",b[0]); // I expect the lower part here which is 0 
    printf("%d\n",b[1]); // I expect the higher part here which is 11111000 
    return 0; 
} 

但我的結果顯示零值。我必須分別複製每個部分嗎?有沒有其他更簡單的方法來做到這一點?

謝謝

+0

這假設您的平臺上的整數只有16位。今天這確實不是一個安全的假設。您應該期望大多數平臺至少實現32位整數。 –

+0

@DavidHoelzer雖然你沒有做出平臺假設(請參閱我在回答中如何避免這一點),但請注意,他在每個平臺上都使用「short」,這是我可以想到的每個平臺上的16位。 –

+0

啊,我沒有真正注意到這個短。我剛纔在問題中看到了「unsigned int」。 :) –

回答

3

嘗試這樣

memcpy(b, &a, sizeof(a)); 

或者

b[0] = a & 0xFF; 
b[1] = (a >> 8) & 0xFF; 

注意bunsigned char類型,以便分配給*b應該是相同類型或值的值將被截斷。

+1

截斷的好解釋,但恐怕你的答案是不完整的:OP應該在字節順序上提出警告。 – chqrlie

5

如果你只是想解釋shortchar數組,你甚至不需要複製。只投:

#include <stdio.h> 
int main() 
{ 
    size_t i; 
    unsigned short a = 63488; 
    unsigned char* b = (unsigned char*)&a; // Cast the address of a to 
               // a pointer-to-unsgigned-char 

    printf("Input value: %d (0x%X)\n", a, a); 

    printf("Each byte:\n"); 
    for (i = 0; i < sizeof(a); i++) 
     printf("b[%d] = %d (0x%X)\n", i, b[i], b[i]); 

    return 0; 
} 

輸出:

$ gcc -Wall -Werror so1.c && ./a.out 
Input value: 63488 (0xF800) 
Each byte: 
b[0] = 0 (0x0) 
b[1] = 248 (0xF8) 

注意,我跑這我的x86 PC平臺,這是一個小端機,這是爲什麼第一個字節的低字節輸入。

另請注意,我的代碼也不會對short的大小做出假設。

+0

如果編譯爲'gcc -Wall -Wextra -Wconversion -pedantic -std = c99 -Werror untitled.c && ./a.out',那麼結果是: 'untitled.c:在函數'main'中: untitled.c :錯誤:有符號和無符號整數表達式之間的比較[-Werror = sign-compare] for(i = 0; i user3629249