I'm writing a program that takes a users input of characters, singles each character, converts each to binary, and also counts the amount of '1's in each binary. So far, I have a working code. However, the output of each binary is in reverse order. Like this:
The character A = 10000010 1's = 2
When what I want/need is:
The character A = 01000001 1's = 2
I am required to use the amount of functions I already have and have been told that fixing this will be as simple as doing recursion on my binaryPrinter function. I'm confused about where I would do that within my function and what arguments I would send through. Any help would be fantastic, thanks.
p.s. I'm required to use recursion in the binaryPrinter function to loop the program which apparently is going to solve my backwards binary problems if I place it in the right part of the binaryPrinter function.
#include <stdio.h>
#include <stdlib.h>
void binaryPrinter(int digitsLeft, int value, int * numberOfOnes);
void print(char c);
int charToInt(char C)
{
int c;
c=C;
return (int) c;
}
int main ()
{
char value;
int result = 1;
while (result != EOF)
{
result = scanf("%c", &value);
if (result != EOF)
{
print(value);
}
}
}
void print(char c)
{
int digits=8, value=c;
int ones=0;
printf("The character %c = ", c);
binaryPrinter(digits, value, &ones );
printf(" 1's = %d\n", ones);
}
void binaryPrinter(int digitsLeft, int value, int * numberOfOnes)
{
for (digitsLeft=8; digitsLeft>0; digitsLeft--)
{
if( value & 1 )
{
printf("1");
*numberOfOnes=*numberOfOnes+1;
}
else
{
printf("0");
}
value = value >> 1;
}
}
Here's the recursive version. Notice that it recurses before printing anything, so it prints as it's returning from processing each digit, which prints them in the proper order.
void binaryPrinter(int digitsLeft, int value, int * numberOfOnes)
{
if (digitsLeft > 1) {
binaryPrinter(digitsLeft - 1, value >> 1, numberOfOnes);
}
if (value & 1) {
printf("1");
(*numberOfOnes)++;
} else {
printf("0");
}
}
Change the loop to
for (digitsLeft=1; digitsLeft<=8; digitsLeft++)
Well, you are looking at the digits in reverse order:
if (value & 1) --> take the right-most digit
value = value >> 1; --> shift to the right
so if you have
12345678
(yes, that's not bits, this is just to illustrate the positioning) for inputs, you're doing:
8,7,6,5,4,3,2,1
for output. You need to reverse the logic by working from the left (highest) bits in your original string and work yourway down to the least significant bits.
Related
As a C fresher, I am trying to write a recursive routine to convert a decimal number to the equivalent binary. However, the resultant string is not correct in the output. I think it has to be related to the Type casting from int to char. Not able to find a satisfactory solution. Can anyone help? Thanx in advance.
Code:
#include <stdio.h>
#include <conio.h>
int decimal, counter=0;
char* binary_string = (char*)calloc(65, sizeof(char));
void decimal_to_binary(int);
int main()
{
puts("\nEnter the decimal number : ");
scanf("%d", &decimal);
decimal_to_binary(decimal);
*(binary_string + counter) = '\0';
printf("Counter = %d\n", counter);
puts("The binary equivalent is : ");
puts(binary_string);
return 0;
}
void decimal_to_binary(int number)
{
if (number == 0)
return;
else
{
int temp = number % 2;
decimal_to_binary(number/2);
*(binary_string + counter) = temp;
counter++;
}
}
Should the casting store only the LSB of int in the char array each time?
Do not use global variables if not absolutely necessary. Changing the global variable in the function makes it very not universal.
#include <stdio.h>
char *tobin(char *buff, unsigned num)
{
if(num / 2) buff = tobin(buff, num / 2);
buff[0] = '0' + num % 2;
buff[1] = 0;
return buff + 1;
}
int main(void)
{
char buff[65];
unsigned num = 0xf1;
tobin(buff, num);
printf("%s\n", buff);
}
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int decimal, counter=0;
//char* binary_string = (char*)calloc(65, sizeof(char));
//C does not allow initialization of global variables with
//non constant values. Instead declare a static char array with 65 elements.
//Alternatively declare binary_string in the main function and allocate memory with calloc.
char binary_string[65];
void decimal_to_binary(int);
int main()
{
puts("\nEnter the decimal number : ");
scanf("%d", &decimal);
decimal_to_binary(decimal);
//*(binary_string + counter) = '\0';
// This is more readable:
binary_string[counter] = '\0';
printf("Counter = %d\n", counter);
puts("The binary equivalent is : ");
puts(binary_string);
return 0;
}
void decimal_to_binary(int number)
{
if (number == 0)
return;
else
{
int temp = number % 2;
//decimal_to_binary(number/2);
//you call decimal_to_binary again before increasing counter.
//That means every time you call decimal_to_binary, the value of count
//is 0 and you always write to the first character in the string.
//*(binary_string + counter) = temp;
//This is more readable
//binary_string[counter] = temp;
//But you are still setting the character at position counter to the literal value temp, which is either 0 or 1.
//if its 0, you are effectively writing a \0 (null character) which in C represents the end of a string.
//You want the *character* that represents the value of temp.
//in ASCII, the value for the *character* 0 is 0x30 and for 1 it is 0x31.
binary_string[counter] = 0x30 + temp;
counter++;
//Now after writing to the string and incrementing counter, you can call decimal_to_binary again
decimal_to_binary(number/2);
}
}
If you compile this, run the resulting executable and enter 16 as a number, you may expect to get 10000 as output. But you get00001. Why is that?
You are writing the binary digits to the string in the wrong order.
The first binary digit you calculate is the least significant bit, which you write to the first character in the string etc.
To fix that aswell, you can do:
void decimal_to_binary(int number){
if(number == 0){
return;
}
else{
int temp = number % 2;
counter++;
//Store the position of the current digit
int pos = counter;
//Don't write it to the string yet
decimal_to_binary(number/2);
//Now we know how many characters are needed and we can fill the string
//in reverse order. The first digit (where pos = 1) goes to the last character in the string (counter - pos). The second digit (where pos = 2) goes to the second last character in the string etc.
binary_string[counter - pos] = 0x30 + temp;
}
}
This is not the most efficient way, but it is closest to your original solution.
Also note that this breaks for negative numbers (consider decimal = -1, -1 % 2 = -1).
I'm struggling to write a recursive way to print a binary number. Here is what I have so far:
int bin(unsigned char n)
{
if (n==0) {
return 0;
} else {
printf("%d", bin(n<<1));
}
}
bin(7)
What seems to be wrong with the logic above?
A few errors such as using << (shift up) instead of >> (shift down). Also not always returning something. I'm surprised the compiler didn't pull you up on that. You don't gain anything from a return value, So you may as well get rid of it.
A simple implementation could look like this. We need to have the wrapped function (bin_recur) to allow us to differentiate between 0 the input value and 0 which signifies its time to stop recursion.
#include <stdio.h>
void bin_recur(unsigned char n)
{
if (n > 0)
{
printf("%d", n & 1);
bin_recur(n >> 1);
}
}
void bin(unsigned char n)
{
if (n == 0)
{
printf("0\n");
} else
{
bin_recur(n);
printf("\n");
}
}
int main()
{
for(unsigned i = 0; i < 10; i++)
{
bin(i);
}
}
The fact that your bin function calls printf is not completely ideal. This is what's known as tight coupling and the function could be more reusable if it was not bound to how it is presented. Perhaps copying to a string is a good way or even using fprintf to print to a file.
Stopping when n is 0 is wrong.
This fails for the trivial case where n is 0 to start with.
What you really need to do is pass down a shift amount as a second argument and stop after 8 bits.
Using the return with value just gets in the way.
Here's some refactored code with a full diagnostic test:
#include <stdio.h>
void
bin2(unsigned char n,int shf)
{
if (shf <= 7) {
bin2(n,shf + 1);
printf("%d", (n >> shf) & 1);
}
}
void
bin(unsigned char n)
{
bin2(n,0);
}
int
main(void)
{
for (unsigned int chr = 0; chr <= 0xFF; ++chr) {
printf("%2.2X: ", chr);
bin((unsigned char) chr);
printf("\n");
}
return 0;
}
please add this lines to your code.
void binary(int n) {
if(n==0)
return;
binary(n/2);
printf("%d",n%2);
}
You need the print call to execute after the recursive function for this to work. Here's an example:
void bin(unsigned char n)
{
if (n > 1) bin(n>>1);
putchar(n&1 ? '1' : '0');
}
int main(void)
{
for (unsigned char i = 255; i; i--) {
printf("%d --> ", i), bin(i);
getchar(); // inspect element if you want
}
}
Link to running code here.
So im fairly new to programming and I ran into something which I cannot figure out.
I'll demonstrate my problem.
int main(void){
int number;
if(number == 1){
number1();
}else if(number == 2){
number2();
}else if(number == 3){
number3();
}else if(number == 4){
number4();
}else if(number == 5){
number5();
}else if(number == 6){
number6();
}else if(number == 7){
number7();
}else if(number == 8){
number8();
}else if(number == 9){
number9();
}else if(number == 0){
number0();
} else if (number >= 10 && <= 19){
number1();
number2(25);
}
}
void number1(int Q){
VGA_box(X + 5 + Q, 20, X+7 + Q, 60, white);
}
void number2(int Q){
VGA_box(X + Q, 20, X+ 20 + Q, 22, white);
VGA_box(X + 18 + Q, 22, X+ 20 + Q, 38, white);
VGA_box(X + Q, 38, X+ 20 + Q, 40, white);
VGA_box(X + Q, 40, X+ 2 + Q, 58, white);
VGA_box(X + Q, 58, X+ 20 + Q, 60, white);
}
Please ignore the functions VGA_box(), since this is just a function to write a line/box.
I'm making a little game and I would like to add a scoreboard, but here is my problem:
Since I'm drawing the numbers (so they look better IMO), I have to call functions, functions which represent a number. So if number = 1, function number1(); is called.
Is there an easy way to call the functions number2(), number5() and number9() if the number is 259? Or lets say; 632. The only possible way I can figure out is to use a lot of if-statements but that will take me a while to do.
Is it possible to use a for-loop which keeps track of what the number is and calls the functions which needed?
Thank you in advance.
You can use an array of pointers to function and a recursive function to reverse the value:
#include <stdio.h>
static void func0(void) { printf("0\n"); }
static void func1(void) { printf("1\n"); }
static void func2(void) { printf("2\n"); }
static void func3(void) { printf("3\n"); }
static void (*func[])(void) = {func0, func1, func2, func3};
static void exec(int value)
{
if (value) {
exec(value / 10);
func[value % 10]();
}
}
int main(void)
{
exec(123);
return 0;
}
Output:
1
2
3
As pointed out by #user3078414 in comments this fails when exec(012) is passed (the first 0 is not evaluated in the recursive function), in addition, 012 is interpreted as an octal (not as a decimal).
An alternative using strings:
#include <stdio.h>
static void func0(void) { printf("0\n"); }
static void func1(void) { printf("1\n"); }
static void func2(void) { printf("2\n"); }
static void func3(void) { printf("3\n"); }
static void (*func[])(void) = {func0, func1, func2, func3};
int main(void)
{
char *ptr = "012";
while (*ptr) {
func[*ptr - '0']();
ptr++;
}
return 0;
}
It seems like functions number1(), number2(), etc are quite similar. I'd be against creating different functions; I'd rather create one single function (let's say number()) which receives the whole number "632" from your example, and loops digit by digit.
Creating one single function is easier to handle by you. Just check that the resulting function is not too big, but it's quite likely that functions number1(), number2(), etc have a lot of code in common. If that's the case, reducing redundancy and repetition in code is highly recommended!
Let me know if I'm right with this.
Cheers!
Create function drawDigit(int digit) where digit is a single digit number between 0 and 9.
You can use function pointers to select which number function to call, but if that is too complex, you can use the if/else method for now.
Convert score to string:
int score = 259;
char digits[SIZE]; // Size must be large enough to hold all digits and nul character ('\0')
int numDigits = snprintf(digits, SIZE, "%d", score); // snprintf is from "stdio.h"
// digits contains now 4 character string "259" with nul character at the end
Loop over string to draw all digits:
for(int i = 0; i < numDigits; ++i) {
int digit = digits[i] - '0'; // Convert character digit to numeric digit
drawDigit(digit);
}
You probably need extra a parameter to drawDigit function to adjust the horizontal placement, but I'll leave that exercise to the reader.
Function pointers and switch/case are not the solution !
The problem is not if-statement or even the functions. Since your algorithms to draw scores are very different in each function then you can not stop using lots of conditions, so you have to some where call them by lots of if statements.
The solution is to find an uniform algorithm to draw scores on the screen for every number. For example write 10 functions to draw digits between [0..9], then use this functions to draw numbers with arbitrary length numbers.
You can use pointer to function, e.g:
#include <stdio.h>
typedef void (*typ_callback)(int);
static void number1(int Q);
static void number2(int Q);
typ_callback my_table[] = { NULL, number1, number2 };
int main(void)
{
size_t number;
printf("Entern the number of callback: ");
scanf("%zu", &number);
if (number <= (sizeof(my_table)/sizeof(my_table[0])))
{
if (my_table[number] != NULL)
{
my_table[number](number);
}
}
else
{
fprintf(stderr, "Wrong number\n");
}
return 0;
}
static void number1(int Q)
{
printf("You called %s function with passing value %d\n", __func__, Q);
}
static void number2(int Q)
{
printf("You called %s function with passing value %d\n", __func__, Q);
}
I have the following working code; it accepts a string input as the function parameter and spits out the same string converted to a decimal.
I'm not going to bother accounting for negative inputs, although I understand that I can set a boolean flag to true when the first indexed character is a "-". If the flag switches to true, take the total output and multiply by -1.
Anyway, I'm pretty stuck on where to go from here; I'd like to adjust my code so that I can account for a decimal place. Multiplying by 10 and adding the next digit (after converting that digit from an ASCII value) yields an integer that is displayed in decimal in the output. This obviously won't work for numbers that are smaller than 1. I understand why (but not really how) to identify where the decimal point is and say that "for anything AFTER this string index containing a decimal point, do this differently"). Also, I know that instead of multiplying by a power of 10 and adding the next number, I have to multiply by a factor of -10, but I'm not sure how this fits into my existing code...
#include <stdio.h>
#include <string.h>
int num = 0;
int finalValue(char *string1) {
int i = 0;
if (string1[i] != '\0') {
if (string1[i]<'0' || string1[i]>'9') {
printf("Sorry, we can't convert this to an integer\n\n");
}
else {
num *= 10;
num += string1[i] - '0';
//don't bother using a 'for' loop because recursion is already sort-of a for loop
finalValue(&string1[i+1]);
}
}
return num;
}
int main(int argc, const char * argv[]) {
printf("string to integer conversion yields %i\n",(finalValue("99256")));
return 0;
}
I made some adjustments to the above code and it works, but it's a little ugly when it comes to the decimal part. For some reason, the actual integer output is always higher than the string put in...the math is wrong somewhere. I accounted for that by subtracting a static amount (and manually multiplying by another negative power of 10) from the final return value...I'd like to avoid doing that, so can anybody see where my math / control flow is going wrong?
#include <stdio.h>
#include <string.h>
//here we are setting up a boolean flag and two variables
#define TRUE 1
#define FALSE 0
double num = 0;
double dec = 0.0;
int flag = 0;
double final = 0.0;
double pow(double x, double y);
//we declare our function that will output a DOUBLE
double finalValue(char *string1) {
//we have a variable final that we will return, which is just a combination of the >1 and <1 parts of the float.
//i and j are counters
int i = 0;
int j = 0;
//this will go through the string until it comes across the null value at the very end of the string, which is always present in C.
if (string1[i] != '\0') {
//as long as the current value of i isn't 'null', this code will run. It tests to see if a flag is true. If it isn't true, skip this and keep going. Once the flag is set to TRUE in the else statement below, this code will continue to run so that we can properly convert the decimal characers to floats.
if (flag == TRUE) {
dec += ((string1[i] - '0') * pow(10,-j));
j++;
finalValue(&string1[i+1]);
}
//this will be the first code to execute. It converts the characters to the left of the decimal (greater than 1) to an integer. Then it adds it to the 'num' global variable.
else {
num *= 10;
num += string1[i] - '0';
// This else statement will continue to run until it comes across a decimal point. The code below has been written to detect the decimal point and change the boolean flag to TRUE when it finds it. This is so that we can isolate the right part of the decimal and treat it differently (mathematically speaking). The ASCII value of a '.' is 46.
//Once the flag has been set to true, this else statement will no longer execute. The control flow will return to the top of the function, and the if statement saying "if the flag is TRUE, execute this' will be the only code to run.
if (string1[i+1] == '.'){
flag = TRUE;
}
//while this code block is running (before the flag is set to true) use recursion to keep converting characters into integers
finalValue(&string1[i+1]);
}
}
else {
final = num + dec;
return final;
}
return final;
}
int main(int argc, const char * argv[]) {
printf("string to integer conversion yields %.2f\n",(finalValue("234.89")));
return 0;
}
I see that you have implemented it correctly using global variables. This works, but here is an idea on how to avoid global variables.
A pretty standard practice is adding parameters to your recursive function:
double finalValue_recursive(char *string, int flag1, int data2)
{
...
}
Then you wrap your recursive function with additional parameters into another function:
double finalValue(char *string)
{
return finalValue_recursive(string, 0, 0);
}
Using this template for code, you can implement it this way (it appears that only one additional parameter is needed):
double finalValue_recursive(char *s, int pow10)
{
if (*s == '\0') // end of line
{
return 0;
}
else if (*s == '-') // leading minus sign; I assume pow10 is 0 here
{
return -finalValue_recursive(s + 1, 0);
}
else if (*s == '.')
{
return finalValue_recursive(s + 1, -1);
}
else if (pow10 == 0) // decoding the integer part
{
int digit = *s - '0';
return finalValue_recursive(s + 1, 0) * 10 + digit;
}
else // decoding the fractional part
{
int digit = *s - '0';
return finalValue_recursive(s + 1, pow10 - 1) + digit * pow(10.0, pow10);
}
}
double finalValue(char *string)
{
return finalValue_recursive(string, 0);
}
Also keep track of the occurrence of the decimal point.
int num = 0;
const char *dp = NULL;
int dp_offset = 0;
int finalValue(const char *string1) {
int i = 0;
if (string1[i] != '\0') {
if (string1[i]<'0' || string1[i]>'9') {
if (dp == NULL && string1[i] == '.') {
dp = string1;
finalValue(&string1[i+1]);
} else {
printf("Sorry, we can't convert this to an integer\n\n");
} else {
} else {
num *= 10;
num += string1[i] - '0';
finalValue(&string1[i+1]);
}
} else if (dp) {
dp_offset = string1 - dp;
}
return num;
}
After calling finalValue() code can use the value of dp_offset to adjust the return value. Since this effort may be the beginning of a of a complete floating-point conversion, the value of dp_offset can be added to the exponent before begin applied to the significand.
Consider simplification
//int i = 0;
//if (string1[i] ...
if (*string1 ...
Note: using recursion here to find to do string to int is a questionable approach especially as it uses global variables to get the job done. A simply function would suffice. Something like untested code:
#include <stdio.h>
#include <stdlib.h>
long long fp_parse(const char *s, int *dp_offset) {
int dp = '.';
const char *dp_ptr = NULL;
long long sum = 0;
for (;;) {
if (*s >= '0' && *s <= '9') {
sum = sum * 10 + *s - '0';
} else if (*s == dp) {
dp_ptr = s;
} else if (*s) {
perror("Unexpected character");
break;
} else {
break;
}
s++;
}
*dp_offset = dp_ptr ? (s - dp_ptr -1) : 0;
return sum;
}
Figured it out:
#include <stdio.h>
#include <string.h>
//here we are setting up a boolean flag and two variables
#define TRUE 1
#define FALSE 0
double num = 0;
double dec = 0.0;
int flag = 0;
double final = 0.0;
double pow(double x, double y);
int j = 1;
//we declare our function that will output a DOUBLE
double finalValue(char *string1) {
//i is a counter
int i = 0;
//this will go through the string until it comes across the null value at the very end of the string, which is always present in C.
if (string1[i] != '\0') {
double newGuy = string1[i] - 48;
//as long as the current value of i isn't 'null', this code will run. It tests to see if a flag is true. If it isn't true, skip this and keep going. Once the flag is set to TRUE in the else statement below, this code will continue to run so that we can properly convert the decimal characers to floats.
if (flag == TRUE) {
newGuy = newGuy * pow(10,(j)*-1);
dec += newGuy;
j++;
finalValue(&string1[i+1]);
}
//this will be the first code to execute. It converts the characters to the left of the decimal (greater than 1) to an integer. Then it adds it to the 'num' global variable.
else {
num *= 10;
num += string1[i] - '0';
// This else statement will continue to run until it comes across a decimal point. The code below has been written to detect the decimal point and change the boolean flag to TRUE when it finds it. This is so that we can isolate the right part of the decimal and treat it differently (mathematically speaking). The ASCII value of a '.' is 46.
//Once the flag has been set to true, this else statement will no longer execute. The control flow will return to the top of the function, and the if statement saying "if the flag is TRUE, execute this' will be the only code to run.
if (string1[i+1] == 46){
flag = TRUE;
finalValue(&string1[i+2]);
}
//while this code block is running (before the flag is set to true) use recursion to keep converting characters into integers
finalValue(&string1[i+1]);
}
}
else {
final = num + dec;
return final;
}
return final;
}
int main(int argc, const char * argv[]) {
printf("string to integer conversion yields %.2f\n",(finalValue("234.89")));
return 0;
}
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int myatoi(const char* string) {
int i = 0;
while (*string) {
i = (i << 3) + (i<<1) + (*string -'0');
string++;
}
return i;
}
void decimal2binary(char *decimal, int *binary) {
decimal = malloc(sizeof(char) * 32);
long int dec = myatoi(decimal);
long int fraction;
long int remainder;
long int factor = 1;
long int fractionfactor = .1;
long int wholenum;
long int bin;
long int onechecker;
wholenum = (int) dec;
fraction = dec - wholenum;
while (wholenum != 0 ) {
remainder = wholenum % 2; // get remainder
bin = bin + remainder * factor; // store the binary as you get remainder
wholenum /= 2; // divide by 2
factor *= 10; // times by 10 so it goes to the next digit
}
long int binaryfrac = 0;
int i;
for (i = 0; i < 10; i++) {
fraction *= 2; // times by two first
onechecker = fraction; // onechecker is for checking if greater than one
binaryfrac += fractionfactor * onechecker; // store into binary as you go
if (onechecker == 1) {
fraction -= onechecker; // if greater than 1 subtract the 1
}
fractionfactor /= 10;
}
bin += binaryfrac;
*binary = bin;
free(decimal);
}
int main(int argc, char **argv) {
char *data;
data = malloc(sizeof(char) * 32);
int datai = 1;
if (argc != 4) {
printf("invalid number of arguments\n");
return 1;
}
if (strcmp(argv[1], "-d")) {
if (strcmp(argv[3], "-b")) {
decimal2binary(argv[2], &datai);
printf("output is : %d" , datai);
} else {
printf("invalid parameter");
}
} else {
printf("invalid parameter");
}
free(data);
return 0;
}
In this problem, myatoi works fine and the decimal2binary algorithm is correct, but every time I run the code it gives my output as 0. I do not know why. Is it a problem with pointers? I already set the address of variable data but the output still doesn't change.
./dec2bin "-d" "23" "-b"
The line:
long int fractionfactor = .1;
will set fractionfactor to 0 because the variable is defined as an integer. Try using a float or double instead.
Similarly,
long int dec = myatoi(decimal);
stores an integer value, so wholenum is unnecessary.
Instead of
i = (i << 3) + (i<<1) + (*string -'0');
the code will be much more readable as
i = i * 10 + (*string - '0');
and, with today's optimizing compilers, both versions will likely generate the same object code. In general, especially when your code isn't working, favor readability over optimization.
fraction *= 2; // times by two first
Comments like this, that simply translate code to English, are unnecessary unless you're using the language in an unusual way. You can assume the reader is familiar with the language; it's far more helpful to explain your reasoning instead.
Another coding tip: instead of writing
if (strcmp(argv[1], "-d")) {
if (strcmp(argv[3], "-b")) {
decimal2binary(argv[2], &datai);
printf("output is : %d" , datai);
} else {
printf("invalid parameter");
}
} else {
printf("invalid parameter");
}
you can refactor the nested if blocks to make them simpler and easier to understand. In general it's a good idea to check for error conditions early, to separate the error-checking from the core processing, and to explain errors as specifically as possible so the user will know how to correct them.
If you do this, it may also be easier to realize that both of the original conditions should be negated:
if (strcmp(argv[1], "-d") != 0) {
printf("Error: first parameter must be -d\n");
else if (strcmp(argv[3], "-b") != 0) {
printf("Error: third parameter must be -b\n");
} else {
decimal2binary(argv[2], &datai);
printf("Output is: %d\n" , datai);
}
void decimal2binary(char *decimal, int *binary) {
decimal = malloc(sizeof(char) * 32);
...
}
The above lines of code allocate a new block of memory to decimal, which will then no longer point to the input data. Then the line
long int dec = myatoi(decimal);
assigns the (random values in the) newly-allocated memory to dec.
So remove the line
decimal = malloc(sizeof(char) * 32);
and you will get the correct answer.
if(!strcmp(argv[3] , "-b"))
if(!strcmp(argv[3] , "-d"))
The result of the string compare function should be negated so that you can proceed. Else it will print invalid parameter. Because the strcmp returns '0' when the string is equal.
In the 'decimal2binary' function you are allocating a new memory block inside the function for the input parameter 'decimal',
decimal = malloc(sizeof(char) * 32);
This would actually overwrite your input parameter data.