Reputation:
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
Upvotes: 0
Views: 1368
Reputation: 109
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;
}
Upvotes: 0
Reputation: 71
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)"
Upvotes: 0
Reputation: 104559
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];
Upvotes: 2