C++将字符串转换为 int 的奇怪输出

发布于 2024-09-24 21:55:43 字数 709 浏览 2 评论 0原文

我正在编写一个将二进制字符串转换为十进制的程序。在真正开始使用此方法之前,我想验证我的输出。我有以下代码:

int get_val()
    {
        int sum =0;
        for(int num_bits = size; num_bits>0; num_bits--)
        {
            printf("String sub %i is %i\n", num_bits, int(bin[num_bits]));
        }
    }

当我输入 16 个零的字符串时,我得到以下输出:

String sub 16 is 24
String sub 15 is 0
String sub 14 is 0
String sub 13 is 0
String sub 12 is 23
String sub 11 is 0
String sub 10 is 0
String sub 9 is 0
String sub 8 is 22
String sub 7 is 0
String sub 6 is 0
String sub 5 is 0
String sub 4 is 21
String sub 3 is 0
String sub 2 is 0
String sub 1 is 0

为什么如果我输入全零,我会得到不同的值?

编辑:bin 是“0000000000000000”

I'm writing a program that converts a binary string to decimal. I wanted to validate my output before I get really started on this method. I have the following code:

int get_val()
    {
        int sum =0;
        for(int num_bits = size; num_bits>0; num_bits--)
        {
            printf("String sub %i is %i\n", num_bits, int(bin[num_bits]));
        }
    }

When I input a string of 16 zeros, I get the following output:

String sub 16 is 24
String sub 15 is 0
String sub 14 is 0
String sub 13 is 0
String sub 12 is 23
String sub 11 is 0
String sub 10 is 0
String sub 9 is 0
String sub 8 is 22
String sub 7 is 0
String sub 6 is 0
String sub 5 is 0
String sub 4 is 21
String sub 3 is 0
String sub 2 is 0
String sub 1 is 0

Why would I bet getting different values if I input all zeros?

EDIT: bin is "0000000000000000"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空城旧梦 2024-10-01 21:55:43

只要问题没有更新,也许这个示例代码会有帮助。它将二进制字符串转换为整数。我尝试保留尽可能多的代码和变量名称。

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

using namespace std;

int main() {
    string bin = "000111010";
    int size = bin.length();
    int sum = 0;
    for(int num_bits = 1; num_bits <= size; num_bits++) {
      sum <<= 1;
      sum += bin[num_bits - 1] - '0';
    }
    printf("Binary string %s converted to integer is: %i\n", bin.c_str(), sum);
}

正如评论中已经说过的,这里的主要技巧是将 ASCII 字符“0”和“1”转换为整数 0 和 1,这是通过减去“0”的值来完成的。另外,我更改了字符串的遍历顺序,因为这样,您可以在每位之后移动整数并始终设置当前最低位的值。

As long as the question isn't updated, perhaps this example code helps. It converts a binary string into an integer. I tried to keep as much of your code and variable names as possible.

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

using namespace std;

int main() {
    string bin = "000111010";
    int size = bin.length();
    int sum = 0;
    for(int num_bits = 1; num_bits <= size; num_bits++) {
      sum <<= 1;
      sum += bin[num_bits - 1] - '0';
    }
    printf("Binary string %s converted to integer is: %i\n", bin.c_str(), sum);
}

As already said in the comments, the main trick here is to convert the ASCII characters '0' and '1' to the integers 0 and 1 which is done by subtracting the value of '0'. Also, I changed the traverse order of the string because this way, you can shift the integer after each bit and always set the value of the currently lowest bit.

口干舌燥 2024-10-01 21:55:43

简短的回答,你不会。

答案很长,这有一些问题。第一个大问题是,如果我们假设 bin 是长度为“size”的标准字符数组,那么您的第一次打印是无效的。数组索引偏离 1。考虑代码示例:

int size = 16;
char * bin = new char[size];

for(int i=0; i<size; i++)
{
    bin[i] = 0;
}

for(int num_bits = size; num_bits>0; num_bits--)
{
    printf("String sub %i is %i\n", num_bits, int(bin[num_bits]));
}

生成:

String sub 16 is -3
String sub 15 is 0
String sub 14 is 0
String sub 13 is 0
String sub 12 is 0
String sub 11 is 0
String sub 10 is 0
String sub 9 is 0
String sub 8 is 0
String sub 7 is 0
String sub 6 is 0
String sub 5 is 0
String sub 4 is 0
String sub 3 is 0
String sub 2 is 0
String sub 1 is 0

根据您得到的实际输出判断,我猜您做了类似的操作:

int size=16;
int * ints = new int[size];
char * bin;

//Fill with numbers, not zeros, based on the evidence
for(int i=0; i<size; i++)
{
    ints[i] = 20 + i;
}

//Copy over to character buffer
bin = (char*)(void*)&(ints[0]);

for(int num_bits = size; num_bits>0; num_bits--)
{
    printf("String sub %i is %i\n", num_bits, int(bin[num_bits]));
}

这完美地解释了您看到的输出。因此,我认为您的输入假设 bin 指向字符零数组是不正确的。假设你做了类似的事情,那么这会带来一些非常大的问题。

  1. 您认为内存全为零的假设是错误的,您需要对此进行解释或发布真正的代码,我们将
  2. 您不能只将整数的内存缓冲区视为字符 - 字符串由一个字节字符组成(通常),整数为 4 个字节,通常
  3. C++ 中的数组从 0 开始,而不是 1
  4. 将字符转换为整数 [ int('0') ] 不会智能转换 - 由此产生的整数是十进制 48,而不是十进制 0 (有一个函数 atoi 可以做到这一点,以及其他更好的函数,或者使用减法的其他建议)

Short answer, you wouldn't.

Long answer, there are a few issues with this. The first big issue is that if we assume bin is a standard array of characters of length "size", then your first print is invalid. The array index is off by 1. Consider the code example:

int size = 16;
char * bin = new char[size];

for(int i=0; i<size; i++)
{
    bin[i] = 0;
}

for(int num_bits = size; num_bits>0; num_bits--)
{
    printf("String sub %i is %i\n", num_bits, int(bin[num_bits]));
}

Which produces:

String sub 16 is -3
String sub 15 is 0
String sub 14 is 0
String sub 13 is 0
String sub 12 is 0
String sub 11 is 0
String sub 10 is 0
String sub 9 is 0
String sub 8 is 0
String sub 7 is 0
String sub 6 is 0
String sub 5 is 0
String sub 4 is 0
String sub 3 is 0
String sub 2 is 0
String sub 1 is 0

Judging by the actual output you got, I'm guessing you did something like:

int size=16;
int * ints = new int[size];
char * bin;

//Fill with numbers, not zeros, based on the evidence
for(int i=0; i<size; i++)
{
    ints[i] = 20 + i;
}

//Copy over to character buffer
bin = (char*)(void*)&(ints[0]);

for(int num_bits = size; num_bits>0; num_bits--)
{
    printf("String sub %i is %i\n", num_bits, int(bin[num_bits]));
}

That explains the output you saw perfectly. So, I'm thinking your input assumption, that bin points to an array of character zeros, is not true. There are a few really big problems with this, assuming you did something like that.

  1. Your assumption that the memory is all zero is wrong, and you need to explain that or post the real code and we will
  2. You can't just treat a memory buffer of integers as characters - a string is made up of one byte characters (typically), integers are 4 bytes, typically
  3. Arrays in C++ start at 0, not 1
  4. Casting a character to an integer [ int('0') ] does not intelligently convert - the integer that comes out of that is a decimal 48, not a decimal 0 (there is a function atoi that will do that, as well as other better ones, or the other suggestion to use subtraction)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文