C++将字符串转换为 int 的奇怪输出
我正在编写一个将二进制字符串转换为十进制的程序。在真正开始使用此方法之前,我想验证我的输出。我有以下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只要问题没有更新,也许这个示例代码会有帮助。它将二进制字符串转换为整数。我尝试保留尽可能多的代码和变量名称。
正如评论中已经说过的,这里的主要技巧是将 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.
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.
简短的回答,你不会。
答案很长,这有一些问题。第一个大问题是,如果我们假设 bin 是长度为“size”的标准字符数组,那么您的第一次打印是无效的。数组索引偏离 1。考虑代码示例:
生成:
根据您得到的实际输出判断,我猜您做了类似的操作:
这完美地解释了您看到的输出。因此,我认为您的输入假设 bin 指向字符零数组是不正确的。假设你做了类似的事情,那么这会带来一些非常大的问题。
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:
Which produces:
Judging by the actual output you got, I'm guessing you did something like:
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.