简体   繁体   English

十进制到二进制转换不起作用

[英]Decimal to Binary conversion not working

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

int myatoi(const char* string) {
  int i = 0;
  while (*string) {
    i = (i << 3) + (i<<1) + (*string -'0');
    string++;
  }
  return i;
}

void decimal2binary(char *decimal, int *binary) {
  decimal = malloc(sizeof(char) * 32);
  long int dec = myatoi(decimal);
  long int fraction;
  long int remainder;
  long int factor = 1;
  long int fractionfactor = .1;
  long int wholenum;
  long int bin;
  long int onechecker;
  wholenum = (int) dec;
  fraction = dec - wholenum;

  while (wholenum != 0 ) {
    remainder = wholenum % 2;  // get remainder
    bin = bin + remainder * factor;  // store the binary as you get remainder
    wholenum /= 2;  // divide by 2
    factor *= 10;  // times by 10 so it goes to the next digit
  }
  long int binaryfrac = 0;
  int i;
  for (i = 0; i < 10; i++) {
    fraction *= 2;  // times by two first
    onechecker = fraction;  // onechecker is for checking if greater than one
    binaryfrac += fractionfactor * onechecker;  // store into binary as you go
    if (onechecker == 1) {
      fraction -= onechecker;  // if greater than 1 subtract the 1
    }   
    fractionfactor /= 10;
  }

  bin += binaryfrac;
  *binary = bin;
  free(decimal);
}

int main(int argc, char **argv) {   
  char *data;
  data = malloc(sizeof(char) * 32);
  int datai = 1;
  if (argc != 4) {
    printf("invalid number of arguments\n");
    return 1;
  }
  if (strcmp(argv[1], "-d")) {  
    if (strcmp(argv[3], "-b")) {
      decimal2binary(argv[2], &datai);
      printf("output is : %d" , datai);
    } else {
      printf("invalid parameter");
    }
  } else {
    printf("invalid parameter");
  }
  free(data);
  return 0;
}

In this problem, myatoi works fine and the decimal2binary algorithm is correct, but every time I run the code it gives my output as 0. I do not know why. 在此问题中, myatoi正常工作,并且decimal2binary算法正确,但是每次运行代码时,其输出都为0。我不知道为什么。 Is it a problem with pointers? 指针有问题吗? I already set the address of variable data but the output still doesn't change. 我已经设置了变量数据的地址,但是输出仍然没有改变。

./dec2bin "-d" "23" "-b"

The line: 该行:

long int fractionfactor = .1;

will set fractionfactor to 0 because the variable is defined as an integer. 会将fractionfactor设置为0因为变量定义为整数。 Try using a float or double instead. 尝试改用floatdouble

Similarly, 同样,

long int dec = myatoi(decimal);

stores an integer value, so wholenum is unnecessary. 存储的整数值,所以wholenum是不必要的。


Instead of 代替

i = (i << 3) + (i<<1) + (*string -'0');

the code will be much more readable as 该代码将更具可读性

i = i * 10 + (*string - '0');

and, with today's optimizing compilers, both versions will likely generate the same object code. 而且,使用当今优化的编译器,这两个版本可能会生成相同的目标代码。 In general, especially when your code isn't working, favor readability over optimization. 通常,尤其是当您的代码无法正常工作时,应优先考虑可读性而不是优化。


fraction *= 2;  // times by two first

Comments like this, that simply translate code to English, are unnecessary unless you're using the language in an unusual way. 除非您以不同寻常的方式使用该语言,否则不需要将诸如此类的代码简单地翻译为英语的注释。 You can assume the reader is familiar with the language; 您可以假定读者熟悉该语言; it's far more helpful to explain your reasoning instead. 相反,解释您的推理要有用得多。

if(!strcmp(argv[3] , "-b"))

if(!strcmp(argv[3] , "-d"))

The result of the string compare function should be negated so that you can proceed. 字符串比较函数的结果应取反,以便您可以继续进行。 Else it will print invalid parameter. 否则它将打印无效的参数。 Because the strcmp returns '0' when the string is equal. 因为当字符串相等时,strcmp返回“ 0”。

In the 'decimal2binary' function you are allocating a new memory block inside the function for the input parameter 'decimal', 在“ decimal2binary”函数中,您正在函数内部为输入参数“ decimal”分配一个新的内存块,

decimal = malloc(sizeof(char) * 32);

This would actually overwrite your input parameter data. 这实际上将覆盖您的输入参数数据。

void decimal2binary(char *decimal, int *binary) {
  decimal = malloc(sizeof(char) * 32);
  ...
}

The above lines of code allocate a new block of memory to decimal , which will then no longer point to the input data. 上面的代码行将一个新的内存块分配给decimal ,这将不再指向输入数据。 Then the line 然后线

long int dec = myatoi(decimal);

assigns the (random values in the) newly-allocated memory to dec . 将新分配的内存(中的随机值)分配给dec

So remove the line 所以删除线

decimal = malloc(sizeof(char) * 32);

and you will get the correct answer. 您将得到正确的答案。

Another coding tip: instead of writing 另一个编码技巧:不用写

if (strcmp(argv[1], "-d")) {  
  if (strcmp(argv[3], "-b")) {
    decimal2binary(argv[2], &datai);
    printf("output is : %d" , datai);
  } else {
    printf("invalid parameter");
  }
} else {
  printf("invalid parameter");
}

you can refactor the nested if blocks to make them simpler and easier to understand. 您可以重构嵌套的if块,使其更简单易懂。 In general it's a good idea to check for error conditions early, to separate the error-checking from the core processing, and to explain errors as specifically as possible so the user will know how to correct them. 通常,最好及早检查错误情况,将错误检查与核心处理分开,并尽可能具体地解释错误,以便用户知道如何纠正错误。

If you do this, it may also be easier to realize that both of the original conditions should be negated: 如果这样做,则可能更容易意识到两个原始条件都应被取反:

if (strcmp(argv[1], "-d") != 0) {  
  printf("Error: first parameter must be -d\n");
else if (strcmp(argv[3], "-b") != 0) {
  printf("Error: third parameter must be -b\n");
} else {
  decimal2binary(argv[2], &datai);
  printf("Output is: %d\n" , datai);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM