2012-06-16 80 views
-1

我把一個int號碼轉換爲二進制,但我需要簽名擴展到16位二進制是011,即我需要打印它在0000000000000011。 我也有在評估一個負數的二進制一個問題,如果它是大於7符號擴展到16位

#include <stdio.h> 
#include <string.h> 
#include <ctype.h> 
#include <stdlib.h> 

void main() 
{ 
    int x; 
    char inst[4][15]={"addi","8"}; 

    int rem, num=0, i=1; 
    int y; 
    int num1 = atoi(inst[1]); 
    if (num1 < 0) 
    { 
     x=atoi(inst[1]); 
     x = (x * -1) -1;    
     printf("x %d",x); 
     while(x > 0) 
     { 
      rem = x % 2; 
      x= x/2; 
      num = (rem * i)+num; 
      i = i * 10; 
      y = num^111; 
     } 
     printf("binary no: %d",y); 
    } 
    else 
    { 
     x = atoi(inst[1]); 
     while(x > 0) 
     {   
      rem = x % 2; 
      x = x/2; 
      num = (rem * i) + num; 
      i = i * 10; 
     } 
     printf("binary no: %d", num); 
    } 
} 
+0

那麼,是什麼在上面的代碼呢? –

+0

@SherineShafei你的代碼有這麼多的冗餘... –

+0

這段代碼將字符串內部的整數轉換爲整數然後再轉換爲二進制數我需要將此二進制數擴展爲16位 –

回答

0

這裏是我的32位代碼integer.Will這會給你一個提示。

1 #include <stdio.h> 
    2 #include <stdlib.h> 
    3 
    4 int 
    5 main(void) 
    6 { 
    7  const char set[] = {'0', '1'}; 
    8  int number; 
    9  unsigned int unumber, tmp; 
10  int i, loop; 
11  char * output, * cpy; 
12 
13 
14  scanf("%d", &number); 
15  unumber = (unsigned int)number; 
16 
17  loop = sizeof(unsigned int) * 8; 
18  output = malloc(loop + 1); 
19  cpy = output + loop; 
20  *cpy = '\0'; 
21  cpy--; 
22 
23  for(i = 0; i < loop; i++) 
24   *cpy-- = set[(unumber >> i & 1)]; 
25 
26 
27  printf("%s\n", output); 
28  free(output); 
29 
30  return 0; 
31 } 
32 

例如輸入和輸出:

10 
00000000000000000000000000001010 
-1 
11111111111111111111111111111111