0

When I try and convert my binary string to int I am receiving a couple of mistakes that I can not figure out. 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

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:

00000000 000000010001001000111010 00000000000000000000000000000001 101010111100110100110001001001000101 

What I get:

0 0 70202 1 -1127017915 
4
  • The 2nd argument of strtol() is useful for error detection/recovery. Commented Feb 3, 2019 at 21:22
  • "First I am reading from a file and the leading zeros are not showing up" --> Why is not showing leading zeros considered a problem? Commented Feb 3, 2019 at 21:24
  • To get the same exact output text as input use printf("%s\n", binaryString) Commented Feb 3, 2019 at 21:24
  • 1
    101010111100110100110001001001000101 is a 36-bit number without a sign. Do expect to store that unchanged in an signed integer less than 37-bit? int is often 32-bit. Commented Feb 3, 2019 at 21:38

3 Answers 3

2

This line:

char* binaryString[100]; 

Is declaring an array of 100 char pointers (or 100 strings). You probably meant this to declare a buffer of 100 characters to be interpreted as a single string:

char binaryString[100]; 
Sign up to request clarification or add additional context in comments.

Comments

0
char *binaryString[100]; 

// You are creating an array of pointers in this scenario, use char binaryString[100] instead;

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

// 101010111100110100110001001001000101 Is a 36 bit number, int (in most implementations) is 32 bit. use long long (64 bit in visual c++) as type and strtoll as function instead.

printf("%i \n",value) 

Must be 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; } 

Comments

0

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'

Change this "printf("%i \n",value)" to "printf("%x\n",value)"

Comments