简体   繁体   English

C ++二进制到十进制和反向转换器

[英]C++ Binary to Decimal and Back Converter

I've almost solved this exercise: Binary to Decimal and Back Converter - "Develop a converter to convert a decimal number to binary or a binary number to its decimal equivalent." 我几乎解决了这个问题:二进制到十进制和反向转换器-“开发一个转换器,将十进制数转换为二进制或将二进制数转换为等效的十进制。” So, the binary to decimal converter works perfectly, but the other one doesn't. 因此,二进制到十进制转换器可以完美地工作,而另一个则不能。 convertToBinary() function returns crap and I don't know why. convertToBinary()函数返回废话,我不知道为什么。 Here is the code: 这是代码:

#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;

char* convertToBinary(int dec);
int convertToDec(const char* bin);

int main()
{
    std::cout << convertToBinary(100) << std::endl; // wtf!
    return 0;
}

char* convertToBinary(int dec)
{
    char binary[15] = "";
    int result;
    for(int i = 0; dec >= 1; dec /= 2, ++i)
    {
      result = !((dec % 2) == 0);
      binary[i] = result + 48;
    }
    for(int i = strlen(binary); strlen(binary) % 4 != 0; ++i) // add some zeros to make it look cool
      binary[i] = '0';
    for(int i = 0, j = strlen(binary)-1; i < j; ++i, --j) // reverse the array
    {
      char temp = binary[i];
      binary[i] = binary[j];
      binary[j] = temp;
    }
    std::cout << binary << std::endl; // looking good!
    return binary;
}

int convertToDec(const char* bin)
{
    int dec = 0;
    int size = strlen(bin);
    for(int i = 0; *bin; ++i, ++bin)
    {
      int ch = *bin - 48;
      dec += ch * pow(2, size - i - 1);
    }
    return dec;
}

Using c language 使用C语言

char *convertToBinary(int value)
{
    char   *binary;
    size_t  length;
    size_t  i;   

    length = 8 * sizeof(value);
    binary = malloc(1 + length);
    if (binary == NULL)
        return NULL;
    for (i = 0 ; i < length ; ++i)
        binary[length - i - 1] = (value & (1 << i)) ? '1' : '0';
    binary[length] = '\0';

    return binary;
}

int binaryToDecimal(const char *binary)
{
    int    value;
    size_t length;
    size_t i;

    value  = 0;
    length = strlen(binary);

    for (i = 0 ; i < length ; i++)
        value |= (binary[i] == '1') ? (1 << (length - i - 1)) : 0;
    return value;
}

Using c++ language 使用C ++语言

std::string convertToBinary(int value)
{
    std::string binary;
    size_t      length;

    length = 8 * sizeof(value);

    binary.resize(length);
    for (size_t i = 0 ; i < length ; ++i)
        binary[length - i - 1] = (value & (1 << i)) ? '1' : '0';
    return binary;
}

int binaryToDecimal(const std::string &binary)
{
    int    value;
    size_t length;

    value  = 0;
    length = binary.length();

    for (size_t i = 0 ; i < length ; i++)
        value |= (binary[i] == '1') ? (1 << (length - i - 1)) : 0;
    return value;
}

to convert from binary to decimal, you can use strtol of course. 从二进制转换为十进制,您当然可以使用strtol

Your mistake is returning a local variable, a local variable is automatically deallocated when the function returns, and hence the garbage you got. 您的错误是返回局部变量,当函数返回时,局部变量会自动释放,因此您将得到垃圾。

When you do something like this: 当您执行以下操作时:

char *toString(...)
{
    char res[MAX_RES];

    // fill res
    return res;
}

you create the array res as a local array on the stack. 您将数组res创建为堆栈上的本地数组。 This array goes out of scope when you return from the function; 从函数返回时,此数组超出范围。 a pointer to this array is no longer valid and most likely will point to garbage. 指向此数组的指针不再有效,并且很可能会指向垃圾。

If you want to use C-style char buffers, there are two ways to get around this: 如果要使用C样式的char缓冲区,有两种方法可以解决此问题:

Allocate the result on the heap. 在堆上分配结果。

char *toString(...)
{
    char *res = malloc(MAX_RES);

    // fill res
    return res;
}

Data allocated on the heap with malloc will be valid until explicitly released with free . 在使用free显式释放之前,使用malloc在堆上分配的数据将一直有效。 The advantage of this approach is that you can make the string as long as you wish. 这种方法的优点是您可以根据需要制作字符串。 Thedrawback is that the allocation might fail. 缺点是分配可能失败。 It is also worth noting that the caller now owns the string and is responsible for free ing it: 还值得注意的是,调用者现在拥有该字符串并负责free它:

char *x = toString(...);

// do stuff with x
free(x);

**Pass the buffer and maximum length ** **通过缓冲区和最大长度**

int toString(char *res, size_t max, ...)
{
    // fill res
}

That is the approach many library functions use, notably snprintf . 这是许多库函数使用的方法,尤其是snprintf The caller has to provide their own buffer and information on the maximum allowable length in order to avoid buffer overflows. 调用者必须提供自己的缓冲区和有关最大允许长度的信息,以避免缓冲区溢出。 This approach must keep track of the buffer size and truncate the result if necessary, possibly maintaining the string null-terminated. 此方法必须跟踪缓冲区大小,并在必要时截断结果,可能会保留以null终止的字符串。 Such functions could be void , but it is customary to return the actual string length or -1 as error indicator. 这样的函数可能是void ,但是习惯上返回实际的字符串长度或-1作为错误指示符。

It is called like this: 它的名称如下:

char x[200];

toString(x, sizeof(x), ...);
// do stuff with x

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

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