Binary to decimal and reverse

This is a discussion on Binary to decimal and reverse within the C Programming forums, part of the General Programming Boards category; I'm trying to write functions that take in a passed value and convert it. For example this function receives a ...

1. Binary to decimal and reverse

I'm trying to write functions that take in a passed value and convert it. For example this function receives a char* to "25" in binary: 11001....right now it runs but it prints out 0 which is obviously wrong, it should be 25. Any pointers appreciated

Code:
```main{
char* str = "11001";
int decNum = binToDec(str);
printf("%d\n", decNum);
}

int binToDec(char* bin) {
int num = *bin;
int output = 0;

for(int i=0; num > 0; i++) {
if(num % 10 == 1) {
output += pow(2, i);
}
num /= 10;
}
return output;
}```

2. Your string literal is not actually a number 11001, it is a string containing ASCII characters.

0==0x30
1==0x31

Ascii Table - ASCII character codes and html, octal, hex and decimal chart conversion

3. Well the way you declare str and initialize it using double-quotes means that it is stored in read-only memory, and effectively is a constant that can not be manipulated. That is not the problem, however, it is when you attempt to assign the character array to num on line 9. What you will get is the ascii value of the character in the first position in the array, if you can even do that assignment.

4. Originally Posted by jwroblewski44
Well the way you declare str and initialize it using double-quotes means that it is stored in read-only memory, and effectively is a constant that can not be manipulated. That is not the problem, however, it is when you attempt to assign the character array to num on line 9. What you will get is the ascii value of the character in the first position in the array, if you can even do that assignment.
So what's a good/simple way to get around that?

5. Instead of a character pointer, use an array.
Code:
`char string[] = "11001";`
Then when you want to convert the string of characters into an integer, the function your looking for is atoi().
Code:
```#include <stdlib.h>

int num = atoi( bin );```
Edit: That will convert your string into eleven-thousand and one. Not quite the right way to convert the string of char from binary to decimal. That I will leave up to you!

HINT: This forum has had this particular question asked before, which is confirmed by my google search.

6. Originally Posted by jwroblewski44
Instead of a character pointer, use an array.
Code:
`char string[] = "11001";`
That makes no difference to the problem at hand whatsoever.

Then when you want to convert the string of characters into an integer, the function your looking for is atoi().
No it's not, that's an awful solution. It would only work for up to 10 zeros and ones, but an int would typically consist of say 32 bits. It also does not reduce the amount of work left to do by any amount. In fact it actually increases the amount of work remaining!

The OP needs to start by learning how to iterate over the characters of a string.

7. johngoodman, in the line 9 of your solution, you seem to think that you are taking the number of the string and writing it in the variable num as if it was a decimal number. That is wrong. You are only taking the first character (either '0' or '1'), and storing its ASCII code (48 or 49, respectively) in num.

That is what jwroblewski44 recommends you to do with atoi().

I would add that pow() is an overkill in your case. It works with floating point and you should stick to integers whenever possible. In this case, you should do:
Code:
`output |= 1 << i;`
However, as iMalc said, this is an awful solution. You are passing through decimal base when there is no need at all. It is slow and, what is worse, it reduces severely the range of numbers you can work with.

You should iterate through the string and set the bits of output according to the '1's and '0's you find. Read something about the difference between '0' and 0 (or '\0'), and read something about operators |, &, ^, <<, and >>.

8. Now say I wanted to do a function like "char* decToBin(int dec)" and do the reverse...would i just do the same thing but in reverse?

9. Here is what i came up with:
Code:
```char* decToBin(int dec){
char* output = "";
while(dec > 0){
if(dec % 2){
output += '1';
}
else{
output += '0';
}
dec /= 2;

}
return output;
}```

10. I guess you have already found out that this doesn't work.

Code:
`char* output = "";`
"output" will point to a read only string (aka string literal) which is empty and you can't just add stuff to it.
You need to either declare "output" as a big enough char array or allocate memory using malloc().

Code:
`output += '1';`
"output" is a pointer and here you try to add the value of '1' to the memory address where it points to.

Bye, Andreas

11. Why wouldn't this work? I get a seg fault

Code:
```int main(){
char* binNum = decToBin(25);
int i = 0;
while(binNum != NULL){
printf("%c", *(binNum+i));
i++;
}
}

char* decToBin(int dec){
char* output[20];
int i = 0;
while(dec > 0){
if(dec % 2){
output[i] += '1';
}
else{
output[i] += '0';
}
dec /= 2;
i++;
}
return *output;
}```

12. Code:
`char * output[20];`
Incorrect declaration. You can either declare a character pointer, or a character array with enough space for 20 ( twenty ) characters. Refer to your documentation on proper pointer and array declarations. Also do read the link about strings in C posted above.

13. Ok so now I'm declaring it like such: char* output = malloc(20*sizeof(char)); ... but when i pass it back to main it prints: 10011 ...which is 19 in binary, not 25...i also changed the return statement to "return output" rather than "return output*"...i should also mentions it still seg faults after it prints the wrong values haha

14. Please post your current code along with any warning or error messages generated by your compiler, if any.

Jim

15. Originally Posted by jimblumberg
Please post your current code along with any warning or error messages generated by your compiler, if any.

Jim

Code:
```int main(){
char* binNum = decToBin(25);
int i = 0;
while(binNum != NULL){
printf("%c", *(binNum+i));
i++;
}

}

char* decToBin(int dec){
char* output = malloc(20*sizeof(char));
int i = 0;
while(dec > 0){
if(dec % 2){
output[i] += '1';
}
else{
output[i] += '0';
}
dec /= 2;
i++;
}
return output;
}```
I'm expecting 19 in binary, which is 11001
But instead, here is what I get:
10011įSegmentation fault (core dumped)

Page 1 of 2 12 Last