Continued Power Function Message - c

I keep getting the error message that my I have an undefined reference to the power function, but I'm not really sure where that is occurring or why my code is coming up with that error because I have used to power function before in this way. If anyone could help me figure out why it isn't working now I would really appreciate it.
#include "stdio.h"
#include "string.h" //Needed for strlen()
#include "math.h"
#define MAX_BITS 32
#define MAX_LENGTH 49
#define NUMBER_TWO 2
#define NUMBER_ONE 1
#define TERMINATOR '\0'
//Code to find the index of where the string ends
int last_index_of(char in_str[], char ch) {
for (int i = 0; i < MAX_LENGTH; i++) {
if(in_str[i] == ch) {
last_index_of == i;
}
}
return last_index_of;
}
//Code to find the start of the fractional aspect
void sub_string(char in_str[], char out_str[], int start, int end){
int i = 0;
while (i < 1) {
out_str[i] = in_str[start] + in_str[end-1];
i++;
}
}
int main()
{
//Declaration of variable
char input[MAX_LENGTH +1]; // +1 for '\0'
int number;
double exponent;
char output[MAX_BITS];
int fraction;
sub_string(input, output, 0, TERMINATOR);
//Input from the user
printf("Enter a floating point value in binary: ");
scanf("%s", input);
//Calculates the Decimal Part
for (int i = 0; i < last_index_of(input, TERMINATOR) ; i++) {
number = number + number + input[i];
}
printf("%d", number);
exponent = -1;
//Calculates the Fractional Part
for (int j = 0; j < last_index_of(input, TERMINATOR); j++) {
if (j == last_index_of) {
fraction = NUMBER_ONE/(pow(NUMBER_TWO, exponent));
printf("%d/n", fraction);
}
else {
fraction = NUMBER_ONE/(pow(NUMBER_TWO, exponent));
printf("%d + ", fraction);
exponent--;
}
}
return 0;
}

Some problems:
you need -lm option to linker to tell it where to find pow function
last_index_of is not correctly written, you use the function name as an internal variable, you can correct it this way:
//Code to find the index of where the string ends
int last_index_of(char in_str[], char ch) {
int ret = 0;
for (int i = 0; i < MAX_LENGTH; i++) {
if(in_str[i] == ch) {
ret = i;
}
}
return ret;
}
Note that you can replace your last_index_of() function by strlen()
as pointed in comment, sub_string() is not functionnal. A corrected version could be:
//Code to find the start of the fractional aspect
void sub_string(char in_str[], char out_str[], int start, int end){
int i = 0;
while (start != end) {
/* warning, bounds are still not tested...*/
out_str[i++] = in_str[start++];
}
out_str[i] = '\0'
}
Instead of calling last_index_of() in your exist for loop condition, you should take its value to re-use it:
for (int j = 0; j < last_index_of(input, TERMINATOR); j++) {
/* Error here: will never be TRUE */
if (j == last_index_of) {
/* ... */
}
else {
/* ... */
}
}
would become:
int last_index = last_index_of(input, TERMINATOR);
for (int j = 0; j < last_index; j++) {
if (j == last_index) {
/* ... */
}
else {
/* ... */
}
}
Another problem, you use number variable without initializing it, you should write int number = 0 instead of int number;
After that, there is also a problem with your logic.
You have some idea of what you want to do, but it is not clear in your code.
It seems that you want
the user to input some string in the form 10010.100111
to split this string into two parts 10010 and 100111
to convert the first part into integer part 10010 -> 18
to convert the second part into fractional part 100111 -> 0.609...
This decomposition may lead you to write this kind of code:
#include "stdio.h"
#include "string.h"
#define MAX_BITS 32
#define MAX_LENGTH 49
//Code to find the index of where the string ends
int last_index_of(char in_str[], char ch)
{
int ret = 0;
for (int i = 0; i < MAX_LENGTH; i++) {
if (in_str[i] == ch) {
ret = i;
}
}
return ret;
}
void sub_string(char in_str[], char out_str[], int start, int end)
{
int i = 0;
while (start != end) {
/* warning, bounds are still not tested... */
out_str[i++] = in_str[start++];
}
out_str[i] = '\0';
}
void split(char *input, char *first, char *second)
{
int idx = last_index_of(input, '.');
sub_string(input, first, 0, idx);
sub_string(input, second, idx + 1, strlen(input));
}
int main()
{
//Declaration of variable
char input[MAX_LENGTH + 1]; // +1 for '\0'
char first[MAX_BITS];
char second[MAX_BITS];
/* Input from the user */
printf("Enter a floating point value in binary: ");
scanf("%s", input);
/* split integer and fractionnal parts */
split(input, first, second);
/* decode integer part */
printf("integer part:\n");
for (int i = strlen(first) - 1, j = 1; i > -1; --i, j <<= 1) {
if (first[i] == '1') {
printf("%d ", j);
}
}
/* decode frac part */
printf("\nfractionnal part:\n");
for (int i = 0; i < strlen(second); ++i) {
if (second[i] == '1') {
printf("1/%d ", 2 << i);
}
}
return 0;
}

Related

Adding the result of X dices with n sides and a constant in C

I have to make a program in which I have to add the result of x dices with n faces plus or minus a constant(C). The input should be a string like this: "xDn+-C" (x, n and C must be a decimal number). For example: "4D5+6" or "6D9-5". The D just means "Dice".
I used a function to randomize the rolls but I don't know how to continue...
void initD6(void) {
srand((unsigned)time( NULL ) );
}
int D6(void) {
return ((rand()%6)+1);
}
int main(){
char Dice[4];
for(i=0; i<5; i++){
Dice[i] = D6();
return 0;
}
I don't know how should I take that input as a string and the adding or substracting, and also don't know what should I do next.
Add a struct:
struct rules
{
int dices;
int facesPerDice;
int offset;
};
Solve the dice problem:
int throwDice(int faces)
{
return (rand() % faces) + 1;
}
int playGame(struct rules rules)
{
int result = 0;
for (int i = 0; i < rules.dices; i++)
result += throwDice(rules.facesPerDice);
return result + rules.offset;
}
Solve the parsing problem:
/**
Converts a string to a unsigned int until an invalid character is found or a null character is found.
You should replace this with the function you normally use to convert a string to a integer.
*/
unsigned int stringToUInt(char *str)
{
unsigned int result = 0;
int charindex = 0;
char currentchar;
while ((currentchar = str[charindex++]) != '\0')
{
if (currentchar < '0' || currentchar > '9')
break;
result *= 10;
result += currentchar - '0';
}
return result;
}
/**
Reads a string and generates a struct rules based on it.
The string is expected to be given in the following format:
[uint]'D'[uint]['+' or '-'][uint]
where:
the first uint is the number of dices to roll
the second uint is the number of faces per dice
the third uint is the offset
Terminates the program if something goes wrong.
*/
struct rules parse(char *str)
{
struct rules result;
result.dices = stringToUInt(str);
while (*(str++) != 'D')
if (*str == '\0')
exit(1);
result.facesPerDice = stringToUInt(str);
while (*(str++) != '+' && *(str-1) != '-')
if (*str == '\0')
exit(1);
result.offset = stringToUInt(str);
result.offset *= (*(str-1) == '+' ? 1 : -1);
return result;
}
Put everything together:
int main(int argc, char *argv[])
{
srand(time(NULL));
char input[] = "3D6+9"; //You could use console input if you want
struct rules rules = parse(input);
int gameResult = playGame(rules);
printf("Game result: %d\n", gameResult);
return 0;
}
Assuming no errors in the input, a function which solves your task is:
int throw_dice(const char* s)
{
int num, sides, res;
sscanf(s,"%iD%i%i", &num, &sides, &res);
for (int i = 0; i < num; ++i) {
res += rand() % sides + 1;
}
return res;
}
For simple string parsing sscanf() is a pretty good function. For more complex tasks it's better to use a regular expression library.
As usual, don't relay on rand() for anything but the most simple dice games, with no money involved.
You can try it with the following full example:
#include <stdio.h>
int throw_dice(const char* s)
{
int num, sides, res;
sscanf(s,"%iD%i%i", &num, &sides, &res);
for (int i = 0; i < num; ++i) {
res += rand() % sides + 1;
}
return res;
}
void throw_multiple_times(const char* s, int times)
{
printf("%s: ", s);
for (int i = 0; i < times; ++i) {
printf("%i ", throw_dice(s));
}
printf("\n");
}
int main(void)
{
srand((unsigned)time(NULL));
const char* s;
throw_multiple_times("4D5+6", 100);
throw_multiple_times("6D9-5", 100);
return 0;
}
Test it here.

Iterate Over Char Array Elements in C

This code is supposed to take a user's input and convert it to binary. The input is grouped into an integer array to store character codes and/or adjacent digits, then each item in the integer array is converted to binary. When the user types "c357", "c" should be converted to 99, then converted to binary. Then, "357" should be converted to binary as well. In the main() function, strlen(convert) does not accurately represent the number of items in array convert, thus only iterating over the first array item.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <string.h>
#define EIGHT_BITS 255
#define SIXTEEN_BITS 65535
#define THIRTY_TWO_BITS 4294967295UL
// DETERMINE NUMBER OF BITS TO OUTPUT
int getBitLength(unsigned long d) {
int l;
if (d <= EIGHT_BITS) {
l = 8;
}
else if (d > EIGHT_BITS && d <= SIXTEEN_BITS) {
l = 16;
}
else if (d > SIXTEEN_BITS && d <= THIRTY_TWO_BITS) {
l = 32;
}
return l;
}
// CONVERT INPUT TO BINARY VALUE
char* convertToBinary(unsigned long int decimal) {
int l = getBitLength(decimal);
static char b[33];
char bin[33];
int i, j, k = 0, r;
b[33] = '\0';
bin[33] = '\0';
printf("Bits................ %ld\n", l);
// creates array
for (i = 0; i < l; i++) {
r = decimal % 2;
decimal /= 2;
b[i] = r;
}
// reverses array for binary value
for (j = l - 1; j >= 0; j--) {
bin[k] = b[j];
strncpy(&bin[k], &b[j], l);
snprintf(&bin[k], l, "%d", b[j]);
k++;
}
printf("Binary Value: %s\n", bin);
return bin;
}
unsigned long int* numbersToConvert(char* input) {
const int MAX_INPUT = 20;
int i, k = 0, z = 0;
char numbers[MAX_INPUT];
unsigned long int *toConvert = malloc(MAX_INPUT * sizeof(int));
numbers[MAX_INPUT] = '\0';
for (i = 0; i < strlen(input); i++) {
if (isdigit(input[i])) {
numbers[z] = input[i];
if (!isdigit(input[i + 1])) {
toConvert[k] = strtol(numbers, NULL, 10);
printf("----- %ld -----\n", toConvert[k]);
z = 0;
}
else {
z++;
}
}
else {
printf("----- %c -----\n", input[i]);
printf("Character Code: %d\n", input[i]);
toConvert[k] = (unsigned long int) input[i];
}
k++;
}
return toConvert;
}
int main(void) {
const int MAX_INPUT = 20;
int i, p;
char input[MAX_INPUT];
unsigned long int* convert;
printf("------- Input --------\n");
scanf("%s", input);
input[MAX_INPUT] = '\0';
// PRINT INPUT AND SIZE
printf("\nInput: %s\n", input);
convert = numbersToConvert(input);
convert[MAX_INPUT] = '\0';
printf("strlen: %ld\n", strlen(convert));
for (i = 0; i < strlen(convert); i++) {
printf("num array: %ld\n", convert[i]);
convertToBinary(convert[i]);
}
return 0;
}
I have attempted to null terminate each string to prevent undefined behavior. I am unsure if certain variables, if any, are meant to be static.
It is hard to read your code.
Here you have something working (converting the number to binary):
static char *reverse(char *str)
{
char *end = str + strlen(str) - 1;
char *saved = str;
int ch;
while(end > str)
{
ch = *end;
*end-- = *str;
*str++ = ch;
}
return saved;
}
char *tostr(char *buff, unsigned long long val)
{
if(buff)
{
char *cpos = buff;
while(val)
{
*cpos++ = (val & 1) + '0';
val >>= 1;
}
*cpos = 0;
reverse(buff);
}
return buff;
}
int main()
{
char buff[128];
printf("%s\n", tostr(buff, 128));
}
https://godbolt.org/z/6sRC4C

String array prints out trash values

So I have an assignment where I should delete a character if it has duplicates in a string. Right now it does that but also prints out trash values at the end. Im not sure why it does that, so any help would be nice.
Also im not sure how I should print out the length of the new string.
This is my main.c file:
#include <stdio.h>
#include <string.h>
#include "functions.h"
int main() {
char string[256];
int length;
printf("Enter char array size of string(counting with backslash 0): \n");
/*
Example: The word aabc will get a size of 5.
a = 0
a = 1
b = 2
c = 3
/0 = 4
Total 5 slots to allocate */
scanf("%d", &length);
printf("Enter string you wish to remove duplicates from: \n");
for (int i = 0; i < length; i++)
{
scanf("%c", &string[i]);
}
deleteDuplicates(string, length);
//String output after removing duplicates. Prints out trash values!
for (int i = 0; i < length; i++) {
printf("%c", string[i]);
}
//Length of new string. The length is also wrong!
printf("\tLength: %d\n", length);
printf("\n\n");
getchar();
return 0;
}
The output from the printf("%c", string[i]); prints out trash values at the end of the string which is not correct.
The deleteDuplicates function looks like this in the functions.c file:
void deleteDuplicates(char string[], int length)
{
for (int i = 0; i < length; i++)
{
for (int j = i + 1; j < length;)
{
if (string[j] == string[i])
{
for (int k = j; k < length; k++)
{
string[k] = string[k + 1];
}
length--;
}
else
{
j++;
}
}
}
}
There is a more efficent and secure way to do the exercise:
#include <stdio.h>
#include <string.h>
void deleteDuplicates(char string[], int *length)
{
int p = 1; //current
int f = 0; //flag found
for (int i = 1; i < *length; i++)
{
f = 0;
for (int j = 0; j < i; j++)
{
if (string[j] == string[i])
{
f = 1;
break;
}
}
if (!f)
string[p++] = string[i];
}
string[p] = '\0';
*length = p;
}
int main() {
char aux[100] = "asdñkzzcvjhasdkljjh";
int l = strlen(aux);
deleteDuplicates(aux, &l);
printf("result: %s -> %d", aux, l);
}
You can see the results here:
http://codepad.org/wECjIonL
Or even a more refined way can be found here:
http://codepad.org/BXksElIG
Functions in C are pass by value by default, not pass by reference. So your deleteDuplicates function is not modifying the length in your main function. If you modify your function to pass by reference, your length will be modified.
Here's an example using your code.
The function call would be:
deleteDuplicates(string, &length);
The function would be:
void deleteDuplicates(char string[], int *length)
{
for (int i = 0; i < *length; i++)
{
for (int j = i + 1; j < *length;)
{
if (string[j] == string[i])
{
for (int k = j; k < *length; k++)
{
string[k] = string[k + 1];
}
*length--;
}
else
{
j++;
}
}
}
}
You can achieve an O(n) solution by hashing the characters in an array.
However, the other answers posted will help you solve your current problem in your code. I decided to show you a more efficient way to do this.
You can create a hash array like this:
int hashing[256] = {0};
Which sets all the values to be 0 in the array. Then you can check if the slot has a 0, which means that the character has not been visited. Everytime 0 is found, add the character to the string, and mark that slot as 1. This guarantees that no duplicate characters can be added, as they are only added if a 0 is found.
This is a common algorithm that is used everywhere, and it will help make your code more efficient.
Also it is better to use fgets for reading input from user, instead of scanf().
Here is some modified code I wrote a while ago which shows this idea of hashing:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define NUMCHAR 256
char *remove_dups(char *string);
int main(void) {
char string[NUMCHAR], temp;
char *result;
size_t len, i;
int ch;
printf("Enter char array size of string(counting with backslash 0): \n");
if (scanf("%zu", &len) != 1) {
printf("invalid length entered\n");
exit(EXIT_FAILURE);
}
ch = getchar();
while (ch != '\n' && ch != EOF);
if (len >= NUMCHAR) {
printf("Length specified is longer than buffer size of %d\n", NUMCHAR);
exit(EXIT_FAILURE);
}
printf("Enter string you wish to remove duplicates from: \n");
for (i = 0; i < len; i++) {
if (scanf("%c", &temp) != 1) {
printf("invalid character entered\n");
exit(EXIT_FAILURE);
}
if (isspace(temp)) {
break;
}
string[i] = temp;
}
string[i] = '\0';
printf("Original string: %s Length: %zu\n", string, strlen(string));
result = remove_dups(string);
printf("Duplicates removed: %s Length: %zu\n", result, strlen(result));
return 0;
}
char *remove_dups(char *str) {
int hash[NUMCHAR] = {0};
size_t count = 0, i;
char temp;
for (i = 0; str[i]; i++) {
temp = str[i];
if (hash[(unsigned char)temp] == 0) {
hash[(unsigned char)temp] = 1;
str[count++] = str[i];
}
}
str[count] = '\0';
return str;
}
Example input:
Enter char array size of string(counting with backslash 0):
20
Enter string you wish to remove duplicates from:
hellotherefriend
Output:
Original string: hellotherefriend Length: 16
Duplicates removed: helotrfind Length: 10

Counting characters in a string or file

I have the following code:
#include "stdafx.h"
#include "string.h"
#include "ctype.h"
/*selection sort*/
void swap(int A[], int j, int k)
{
int p = A[k];
int i;
for (i = 0; i < (k - j); i++)
{
A[k - i] = A[k - i - 1];
}
A[j] = p;
}
/*greatest number in an array*/
int max(int A[], int N, int k)
{
int max = k, i;
for (i = k; i < N; i++)
{
if (A[max] < A[i])
max = i;
}
return max;
}
int count_nonspace(const char* str)
{
int count = 0;
while(*str)
{
if(!isspace(*str++))
count++;
}
return count;
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[256];
int i = 0, j = 0, count[256] = { 0 };
char string[100] = "Hello world";
for (i = 0; i < 100; i++)
{
for (j = 0; j<256; j++)
{
if (tolower(string[i]) == (j))
{
count[j]++;
}
}
}
for (j = 0; j<256; j++)
{
printf("\n%c -> %d \n", j, count[j]);
}
}
Program is calculating the number of apperances of each character in a string. Now it prints the number of apperances of all 256 characters, whereas i want it to prinf only the character with greatest number of apperances in a string. My idea was to use the selection sort method to the array with the nubmer of apperances, but this is not working, thus my question is how to printf only the character with the greatest number of apperances in the string?
If anybody would have doubts, this is NOT my homework question.
EDIT: I've just noticed that this code printf apperances of characters begining with "j" why is that?
I started typing this before the others showed up, so I'll post it anyway. This is probably nearly the most efficient (increasing efficiency would add some clutter) way of getting an answer, but it doesn't include code to ignore spaces, count characters without regard to case, etc (easy modifications).
most_frequent(const char * str)
{
unsigned counts[256];
unsigned char * cur;
unsigned pos, max;
/* set all counts to zero */
memset(counts, 0, sizeof(counts));
/* count occurences of each character */
for (cur = (unsigned char *)str; *cur; ++cur)
++counts[*cur];
/* find most frequent character */
for (max = 0, pos = 1; pos < 256; ++pos)
if ( counts[pos] > counts[max] )
max = pos;
printf("Character %c occurs %u times.\n", max, counts[max]);
}
Create an array with your char as index.
Keep incrementing the value in the array based on the characters read.
Now get the max out of the array which gives you the most occurring char in your input.
Code will look like:
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
int main(void) {
char buf[100];
int i=0,max =0,t=0;
int a[256];
memset(a,0,sizeof(a));
fgets(buf,100,stdin);
buf[strlen(buf)-1] = '\0';
while(buf[i] != '\0')
{
a[(int)buf[i]]++;
i++;
}
i=0;
for(i=0;i<256;i++)
{
if(a[i] > max)
{
max = a[i];
t = i;
}
}
printf("The most occurring character is %c: Times: %d",t,max);
return 0;
}
Here is a solution for that, based on your own solution, and using qsort().
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
struct Frequency
{
int character;
int count;
};
int compare(const void *const lhs, const void *const rhs)
{
return ((struct Frequency *)rhs)->count - ((struct Frequency *)lhs)->count;
}
int main(int argc, char* argv[])
{
int i = 0, j = 0;
struct Frequency count[256];
memset(&count, 0, sizeof(count));
char string[100] = "Hello world";
for (i = 0 ; i < 100 ; i++)
{
for (j = 0 ; j < 256 ; j++)
{
count[j].character = j;
if (tolower(string[i]) == j)
{
count[j].count += 1;
}
}
}
qsort(count, sizeof(count) / sizeof(*count), sizeof(*count), compare);
/* skip the '\0' which was counted many times */
if (isprint(count[1].character))
printf("\nThe most popular character is: %c\n", count[1].character);
else
printf("\nThe most popular character is: \\%03x\n", count[1].character);
for (j = 0 ; j < 256 ; j++)
{
if (isprint(count[j].character))
printf("\n%c -> %d \n", count[j].character, count[j].count);
else
printf("\n\\%03x -> %d \n", count[j].character, count[j].count);
}
}
notice that the '\0' is set for all the remainig bytes in
char string[100] = "Hello world";
so the count of '\0' will be the highest.
You could use strlen() to skip '\0', in the counting loop, but don't
for (i = 0 ; i < strlen(string) ; ++i) ...
do it this way
size_t length = strlen(string);
for (i = 0 ; i < length ; ++i) ...

convert each digit of a decimal number to correcsponding binary

I need to convert the string "12345678" to the value 00010010001101000101011001111000 (the value in binary only without the zeroes on the left).
So I have written this code in c, the problem is that when I run it does nothing, just waits like there is an error until I stop it manually.
Any ideas?
#include <stdio.h>
#include <string.h>
void reduce(char string[]) {
int i=0, j=0, k=0, cnt=0, tmp=4, num;
char arr[4], result[4*strlen(string)];
for (i=0; i<strlen(string); i++) {
num = atoi(string[i]);
while (num != 0) {
arr[j++] = num%2;
num = num/2;
tmp--;
}
while (tmp != 0) {
arr[j++] = 0;
tmp--;
}
j--;
for (k=i*4; k<(i*4+4); k++) {
result[k++] = arr[j--];
}
j = 0;
tmp = 4;
}
printf("The result is: \n");
for (i=0; i<4*strlen(result); i++) {
printf("%d",result[i]);
}
printf("\n");
}
int main() {
char c[8] = "12345678";
reduce(c);
return 0;
}
Lots of small errors in your code, which makes it hard to pin-point a single error. Main problem seems to be you are confusing binary numbers (0, 1) with ASCII digits ("0", "1") and are mis-using string functions.
as mentioned elsewhere, char c[8] = .. is wrong.
atoi(string[i]) cannot work; it expects a string, not a char. Use `num = string[i]-'0';
arr[..] gets the value 'num%2, that is, a numerical value. Better to use '0'+num%2 so it's a character string.
you increment k in result[k++] inside a loop that already increments k
add result[k] = 0; at the end before printing, so strlen works correctly
4*strlen(result) is way too much -- the strlen is what it is.
you might as well do a simple printf("%s\n", result);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reduce(char string[]) {
int i=0, j=0, k=0, cnt=0, tmp=4, num;
char arr[5], result[4*strlen(string)+1];
for (i=0; i<strlen(string); i++) {
num = string[i]-'0';
while (num != 0) {
arr[j++] = '0'+num%2;
num = num/2;
tmp--;
}
while (tmp != 0) {
arr[j++] = '0';
tmp--;
}
arr[j] = 0;
j--;
for (k=i*4; k<(i*4+4); k++) {
result[k] = arr[j--];
}
j = 0;
tmp = 4;
}
result[k] = 0;
printf("The result is: \n");
for (i=0; i<strlen(result); i++) {
printf("%c",result[i]);
}
printf("\n");
}
int main() {
char c[] = "12345678";
reduce(c);
return 0;
}
.. resulting in
The result is:
00010010001101000101011001111000
It seems from your example that the conversion you are attempting is to binary coded decimal rather than binary. That being the case your solution is somewhat over-complicated; you simply need to convert each digit to its integer value then translate the bit pattern to ASCII 1's and 0's.
#include <stdio.h>
void reduce( const char* c )
{
for( int d = 0; c[d] != 0; d++ )
{
int ci = c[d] - '0' ;
for( unsigned mask = 0x8; mask != 0; mask >>= 1 )
{
putchar( (ci & mask) == 0 ? '0' : '1' ) ;
}
}
}
On the other hand if you did intend a conversion to binary (rather than BCD), then if the entire string is converted to an integer, you can directly translate the bit pattern to ASCII 1's and 0's as follows:
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
void reduce( const char* c )
{
unsigned ci = (unsigned)atoi( c ) ;
static const int BITS = sizeof(ci) * CHAR_BIT ;
for( unsigned mask = 0x01 << (BITS - 1); mask != 0; mask >>= 1 )
{
putchar( (ci & mask) == 0 ? '0' : '1' ) ;
}
}
In your main(), do either
char c[ ] = "12345678";
or
char c[9] = "12345678";
if you want to use c as a string. Otherwise, it does not have enough space to store the terminating null character.
Here, I took the liberty to modify the code accordingly to work for you. Check the below code. Hope it's self-explanatoty.
#include <stdio.h>
#include <string.h>
void reduce(char string[]) {
int i=0, j=0, k=0, cnt=0, count = 0; //count added, tmp removed
char arr[4], result[ (4*strlen(string) )+ 1], c; //1 more byte space to hold null
for (i=0; i<strlen(string); i++) {
c = string[i];
count = 4;
while (count != 0) { //constant iteration 4 times baed on 9 = 1001
arr[j++] = '0' + (c%2); //to store ASCII 0 or 1 [48/ 49]
c = c/2;
count--;
}
/* //not required
while (tmp >= 0) {
arr[j++] = 0;
tmp--;
}
*/
j--;
for (k=(i*4); k<((i*4) +4); k++) {
result[k] = arr[j--];
}
j = 0;
memset (arr, 0, sizeof(arr));
}
result[k] = 0;
printf("The result is: %s\n", result); //why to loop when we've added the terminating null? print directly.
/*
for (i=0; i< strlen(result); i++) {
printf("%c",result[i]);
}
printf("\n");
*/
}
int main() {
char c[ ] = "12345678";
reduce(c);
return 0;
}
Output:
[sourav#broadsword temp]$ ./a.out
The result is: 00010010001101000101011001111000
Convert your string to an integer using int num = atoi(c).
Then do
int binary[50];
int q = num,i=0;
while(q != 0)
{
binary[i++] = q%2;
q = q/2;
}
Printing your binary array is reverse order will have your binary equivalent.
Full program:
#include<stdio.h>
int main(){
char c[100];
int num,q;
int binary[100],i=0,j;
scanf("%d",c);
num = atoi(c);
q = num;
while(q!=0){
binary[i++]= q % 2;
q = q / 2;
}
for(j = i -1 ;j>= 0;j--)
printf("%d",binary[j]);
return 0;
}
You can use the below reduce function.
void reduce(char string[])
{
unsigned int in = atoi(string) ;
int i = 0, result[32],k,j;
while (in > 0) {
j = in % 10;
k = 0;
while (j > 0) {
result[i++] = j % 2;
j = j >> 1;
k++;
}
while (k < 4) {
result[i++] = 0;
k++;
}
in = in/10;
}
printf("Result\n");
for(--i;i >= 0; i--) {
printf("%d", result[i]);
}
printf("\n");
}
For 12345678
the output would be 00010010001101000101011001111000, where each character is printed in its binary format.
It might need some adjustments, but it does the job as it is.
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
int i;
int n;
char *str = "12345678";
const int bit = 1 << (sizeof(n)*8 - 1);
n = atoi(str);
for(i=0; i < sizeof(n)*8 ; i++, n <<= 1)
n&bit ? printf("1") : printf("0");
return 0;
}

Resources