简体   繁体   English

将二进制字符串转换为整数

[英]Converting a binary string to integer

When I try and convert my binary string to int I am receiving a couple of mistakes that I can not figure out. 当我尝试将二进制字符串转换为int时,遇到了一些我无法弄清的错误。 First I am reading from a file and the leading zeros are not showing up when I convert and the new line is showing zero. 首先,我正在从文件中读取数据,当我进行转换时,前导零不会出现,新行将显示零。

This code I am using from this questions: Convert binary string to hexadecimal string C 我从以下问题中使用的代码: 将二进制字符串转换为十六进制字符串C

char* binaryString[100];

// convert binary string to integer
int value = (int)strtol(binaryString, NULL, 2);

//output string as int
printf("%i \n",value)

My txt file and what I am expecting as an output: 我的txt文件以及期望输出的内容:

00000000

000000010001001000111010
00000000000000000000000000000001
101010111100110100110001001001000101

What I get: 我得到的是:

0
0
70202
1
-1127017915

This line: 这行:

char* binaryString[100];

Is declaring an array of 100 char pointers (or 100 strings). 声明一个由100个char指针(或100个字符串)组成的数组。 You probably meant this to declare a buffer of 100 characters to be interpreted as a single string: 您可能的意思是声明一个100个字符的缓冲区以解释为单个字符串:

char binaryString[100];

if im understanding this correctly you want to take a binary string so ones and zeros and convert it to a Hex string so 0-F, if so the problem is with the Write not the Convert, you specified '%i' as the written value format, what you need to do for hex is specify '%x' 如果我正确理解了这一点,则希望将一个二进制字符串(即一和零)转换为十六进制字符串(即0-F),如果是写而不是转换的问题,则将'%i'指定为写入值格式,您需要为十六进制执行的操作是指定'%x'

Change this "printf("%i \\n",value)" to "printf("%x\\n",value)" 将此“ printf(”%i \\ n“,value)”更改为“ printf(”%x \\ n“,value)”

char *binaryString[100]; 

// You are creating an array of pointers in this scenario, use char binaryString[100] instead; //在这种情况下,您将创建一个指针数组,请使用char binaryString[100]代替;

int value = (int)strtol(binaryString, NULL, 2);

// 101010111100110100110001001001000101 Is a 36 bit number, int (in most implementations) is 32 bit. // 101010111100110100110001001001000101是一个36位数字, int (在大多数实现中)是32位。 use long long (64 bit in visual c++) as type and strtoll as function instead. 使用long long (在Visual c ++中为64位)作为类型,并使用strtoll作为函数。

printf("%i \n",value)

Must be printf("%lld \\n", value) . 必须为printf("%lld \\n", value)

In summary: 综上所述:

#include "stdio.h"
#include "stdlib.h" // required for strtoll

int main(void)
{
    char str[100] = "101010111100110100110001001001000101";
    long long val = 0;
    val = strtoll(str, NULL, 2);
    //output string as int
    printf("%lld \n", val);
    return 0;
}

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

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