#include<stdio.h>
#include<stdlib.h>
int main() {
long long *a, n, i;
while (0 != 1) {
printf("Enter the number to convert: ");
scanf("%lli", &n);
a = (int*) malloc(n * sizeof (int));
printf("%p", a);
for (i = 0; n > 0; i++) {
a[i] = n % 2;
n = n / 2;
}
printf("\nBinary of Given Number is=");
for (i = i - 1; i >= 0; i--) {
printf("%lli", a[i]);
}
__fpurge(stdin);
getchar();
}
}
I have this code, my teacher request input number 77777777777777777777777777777777777777777777 and convert to binary. But program can't run with this number, it's too long. So anyone can help me, how to input billion number and program can run.
Since your input is too large for an int type you can use a string and manipulate it using the same algorithm.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
bool isZero(const char *s, int len)
{
for (int i = 0; i < len; ++i)
{
if (s[i] != '0')
{
return false;
}
}
return true;
}
void div2(char *s, int len)
{
int remainder = 0;
for (int i = 0; i < len; ++i)
{
int digit = s[i] - '0' + remainder;
remainder = 10 * (digit % 2);
s[i] = '0' + (digit / 2);
}
}
int main()
{
char input[256] = "77777777777777777777777777777777777777777777";
char bits[2048] = { 0 };
int len = strlen(input);
for (int i = 0; i < len; ++i)
{
if (input[i] < '0' || input[i] > '9')
{
printf("%c is not a numeric digit, exiting.\n", input[i]);
return -1;
}
}
int pos = 0;
while (!isZero(input, len))
{
int digit = input[len - 1] - '0';
bits[pos++] = '0' + (digit % 2);
div2(input, len);
}
len = strlen(bits);
while (len--)
{
putchar(bits[len]);
}
putchar('\n');
return 0;
}
Related
I'm having some problem with saveing the vaule of the longest fence.
I tried this:
int longestFence(char input [], int size)
{
int i , max = 0, count = 0;
for(i = 0; i < size ; i++)
{
if(input[i] == '|' && input[i] == '-')
{
count = 1;
}
if(input[i] != input[i + 1])
{
count++ - 1;
}
}
return count;
}
In practice, to detect is the fence is still valid, you just have to check if the current symbol is different or not than the previous one.
You also have to check if the current count is longer or not than the previous longest one.
Besides, I modified the random string generator: the current one is rather inefficient.
In addition, the string generated is not terminated by the Null character. I also modified it.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 10
int longestFence (char input[], int size) {
if (size == 0) return 0;
int max_count = 0;
int count = 1;
for (int i = 1; i < size; ++i) {
if (input[i] != input[i-1]) {
count++;
} else {
if (count > max_count) max_count = count;
count = 1;
}
}
if (count > max_count) max_count = count;
return max_count;
}
int main() {
char string[MAX+1];
char symbols[] = {'|', '-'};
srand (time(NULL));
int length = rand() % (MAX+1);
for (int i = 0; i < length; ++i) {
int val = (rand() / 16) % 2;
string[i] = symbols[val];
}
string[length] = '\0';
printf ("String is: %s\n", string);
printf ("Longest fence = %d\n", longestFence (string, length));
return 0;
}
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
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I need to convert integer to a string, be it negative or positive.
So far i able to convert positive integers to strings using the following code.
But not the negative ones. How can i handle them properly to convert them to strings.
Here is the code that i was using.
Thanks
Rajat!
/*
* C Program which Converts an Integer to String & vice-versa
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
void tostring(char [], int);
int main()
{
char str[10];
int num, result;
printf("Enter a number: ");
scanf("%d", &num);
tostring(str, num);
printf("Number converted to string: %s\n", str);
return 0;
}
void tostring(char str[], int num)
{
int i, rem, len = 0, n;
if(num<0)
{
n=(-1)*(num);
}
else
{
n=num;
}
while (n != 0)
{
len++;
n /= 10;
}
for (i = 0; i < len; i++)
{
rem = num % 10;
num = num / 10;
str[len - (i + 1)] = rem + '0';
}
str[len] = '\0';
}
Before doing anything else, see if n is negative. If it is, start the output with the sign - (make sure len is also one more than it would be otherwise, and that your stringification starts one character later), make n positive, and continue as you were doing it before.
You have to be really wary of "corner-case" like many other have said :
You can't have the positive value of a negative int in an int
The range value of an int is [MIN; +MIN -1], like –2,147,483,648 to 2,147,483,647 for a 4 byte int.
So, if you have –2,147,483,648 and you *-1, you will not have 2,147,483,648 since it will overflow the int capacity
Your loop for finding the len of int is "bad", because you don't take negative number in count (but I suppose this is the purpose of this post) and you don't take car of the corner case 0 ("len" value is 0 but must be 1).
So, how can you make this function ?
1 : Fix the int len calculation
size_t len = 1;
for (int n = number; n <= -10 || 10 <= n; n /= 10) {
++len;
}
2 : Fix the "digit to char" loop
for (size_t i = 0; i < len; ++i) {
str[len - i - 1] = abs(number % 10) + '0';
number /= 10;
}
str[len] = '\0';
There. The only thing that left is to put "-" in the beginning and have an offset for negative case number.
You can have an offset variable (fix the "digit to char loop" if you use it) or you can simply do "++str".
There, you can do the function on your own now, I pratically gived you the answer.
On a funny note, you can skip the "abs" function if you simply do the following :
void tostring(char *str, int number)
{
char *digit = "9876543210123456789" + 9;
size_t len = 1;
if (number < 0) {
// TODO : Put '-' in the first case
// TODO : Make str to be *str[1]
}
for (int n = number; n <= -10 || 10 <= n; n /= 10) {
++len;
}
for (size_t i = 0; i < len; ++i) {
str[len - i - 1] = digit[number % 10];
number /= 10;
}
str[len] = '\0';
}
If you don't understand how this work, take your time and read how pointer work (especially pointer arithmetic).
I have solved the issue by the help from #Amadan .
Here is the code that i am using. Please feel free to tell me a more better way to solve this issue.
Thanks
Rajat
/*
* C Program which Converts an Integer to String & vice-versa
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
void tostring(char [], int);
int main()
{
char str[10];
int num, result;
printf("Enter a number: ");
scanf("%d", &num);
tostring(str, num);
printf("Number converted to string: %s\n", str);
return 0;
}
void tostring(char str[], int num)
{
int i, rem, len = 0, n;
bool flag=0;
if(num<0)
{
n=-num;
flag=1;
}
else
{
n=num;
flag=0;
}
while (n != 0)
{
len++;
n /= 10;
}
if(flag==1)
{
num=-1*num;
str[0]='-';
}
for (i = 0; i < len; i++)
{
rem = num % 10;
num = num / 10;
if(flag==1)
{
str[len - (i)] = rem + '0';
}
else
{
str[len - (i + 1)] = rem + '0';
}
}
if(flag==1)
{
str[len+1] = '\0';
}
else
{
str[len] = '\0';
}
}
Just use sprintf function as below,
sprintf(str,"%i",num);
So the modified code will be,
#include <stdio.h>
#include <string.h>
#include <math.h>
void tostring(char [], int);
int main()
{
char str[10];
int num, result;
printf("Enter a number: ");
scanf("%d", &num);
//tostring(str, num);
sprintf(str,"%i",num);
printf("Number converted to string: %s\n", str);
return 0;
}
void tostring(char str[], int num)
{
int i, rem, len = 0, n;
n =num;
while (n != 0)
{
len++;
n /= 10;
}
for (i = 0; i < len; i++)
{
rem = num % 10;
num = num / 10;
str[len - (i + 1)] = rem + '0';
}
str[len] = '\0';
}
Hope this helps.
Here you have the function which works with any base (you need just to find enough chars to represent digits) but it will not work in one corner case (can you find the case?)
static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUWXYZ";
static char *reverse(char *s, size_t len)
{
size_t pos;
for(pos = 0; pos < len / 2; pos++)
{
char tmp = s[pos];
s[pos] = s[len - pos - 1];
s[len - pos - 1] = tmp;
}
return s;
}
char *toString(char *buff, int n, unsigned base)
{
int saved = n;
char *savedbuff = buff;
n = n < 0 ? -n : n; // <= there is one number which will cause problems. Which one?
do
{
*buff++ = Digits[n % base];
n /= base;
}while(n);
if(saved < 0) *buff++ = '-';
*buff = 0;
return reverse(savedbuff, buff - savedbuff);
}
int main()
{
char buff[50];
printf("%s\n", toString(buff, -255,12)); // 12 base :)
printf("%s\n", toString(buff, -976,10)); // 10 base
printf("%s\n", toString(buff, -976,8)); // or maybe octal ?
return 0;
}
I have some program which decompress some string which is already mentioned here: How to decompres array of char in c. After I finished it I have problem with function free (without it, it works ok). There is some strange behaviour and the last assert fails because of : Aborted; core dumped;
when I debug this program I found that problem is in this cycle:
for (j = 0; j < max - 1; j++) {
vysledek[index] = src[i - pom];
printf("cccc%d\n%s\n", j,vysledek);
printf("xxx%c", src[i - pom]);
index++;
}
it prints:
...
xxx#cccc19
HHeeeeeellllllllooooooooooooooo#####################�
xxx#cccc20
HHeeeeeellllllllooooooooooooooo######################
xxx#cccc21
HHeeeeeellllllllooooooooooooooo#######################
xxx#cccc22
HHeeeeeellllllllooooooooooooooo########################
xxx#cccc23
HHeeeeeellllllllooooooooooooooo#########################Hello______________________________world!
xxx#cccc24
HHeeeeeellllllllooooooooooooooo##########################ello______________________________world!
...
can someone explain me this ? How can Hello world from second assert discover in third one ?
whole program is here:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
char * decompress(const char * src) {
int max = 0;
int pom = 1;
int maxSize = 0;
int index = 0;
int isNumber = 0;
int i;
for (i = 0; src[i] != 0; i++) {
max = 0;
isNumber = 0;
while (isdigit(src[i])) {
int digit = (src[i] - '0');
max = max * 10 + digit;
i++;
isNumber = 1;
}
if (max == 0 && !isNumber) {
max = 1;
}
maxSize = maxSize + max;
}
char *vysledek = (char*) malloc((maxSize) * sizeof (int));
for (i = 0; src[i] != 0; i++) {
max = 0;
pom = 0;
isNumber = 0;
while (isdigit(src[i])) {
int digit = (src[i] - '0');
max = max * 10 + digit;
i++;
pom++;
isNumber = 1;
}
if (!isNumber) {
vysledek[index] = src[i];
//printf("%c", src[i]);
index++;
} else {
i--;
int j;
if (max < 1) {
index--;
}
for (j = 0; j < max - 1; j++) {
vysledek[index] = src[i - pom];
//printf("cccc%d\n%s\n", j,vysledek);
//printf("xxx%c", src[i - pom]);
index++;
}
}
//printf("\n%d\n", index);
}
return vysledek;
}
int main(int argc, char * argv []) {
char * res;
assert(!strcmp(
(res = decompress("Hello world!")),
"Hello world!"));
//free(res);
assert(!strcmp(
(res = decompress("Hello_30world!")),
"Hello______________________________world!"));
//free(res);
assert(!strcmp(
(res = decompress("H2e6l8o15 35w5o6r-2d0!!")),
"HHeeeeeellllllllooooooooooooooo wwwwwoooooor--!!"));
//free(res);
return 0;
}
The problem is, that you compare a null-terminated string with a not-null-terminated string.
In your function decompress() you need to reserve one more int and add the missing \0 to the copied buffer.
char *vysledek = (char*) malloc((maxSize) * sizeof (int) + sizeof(int));
[...]
vysledek[index] = '\0';
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;
}