I want to list combinations of o & 1 recursively using c depending on variables number (number)
the output I want is
000
001
010
011
100
101
110
111
I've tried many algorithms the last one is :
void permute(unsigned number) {
if(number == 0) {
printf("\n");
return;
}
permute(number - 1);
printf("0");
permute(number - 1);
printf("1");
} //permute ends here
void permuteN(unsigned number) {
unsigned i;
for(i = 0; i < number + 1; i++){
permute(i);
}
} //permuteN ends here
I think it gives me the answer but not ordered because I don't know where to put \n;
need your help!
If you are indeed just looking for combinations of 1's and 0's I'd suggest you just count up the numbers and list them in binary.
Take the numerals 0...7 in binary and taking only the last 3 bits (apply mask maybe), and you end up with the same set you specified:
000
001
...
...
111
For n-digit combinations, you need to do 0..2^n - 1
Based off this answer, for one specific case of 3-bits
(Credit to #ChrisLutz and #dirkgently)
#include <stdio.h>
int main(){
int numdigits = 3, j;
for(j=1; j<8; j++)
printbits(j);
}
void printbits(unsigned char v) {
int i;
for(i = 2; i >= 0; i--) putchar('0' + ((v >> i) & 1));
printf("\n");
}
Output:
000
001
010
011
100
101
110
111
All you are actually doing is converting a number to binary.... A simple loop does this without any library calls (aside from printf)...
const unsigned int numbits = 3;
unsigned int bit;
for( bit = 1U << (numbits-1); bit != 0; bit >>= 1 ) {
printf( number&bit ? "1" : "0" );
}
printf( "\n" );
Edited, since you seem to want recursion. You need to have some way to specify how many bits you require. You need to pass this into your recursive routine:
#include <stdio.h>
void permute(unsigned number, unsigned bits)
{
if( bits == 0 ) return;
permute(number / 2, bits-1);
printf( "%d", number % 2 );
} //permute ends here
void permuteN(unsigned number, unsigned bits ) {
unsigned i;
for(i = 0; i < number + 1; i++){
permute(i, bits);
printf("\n");
}
} //permuteN ends here
int main(void)
{
permuteN(7, 3);
return 0;
}
To get the output in the order you require, you can't know when to write the newline. So in this case, you write it afterwards.
#paddy has a nice answer; only adding a bit (as of my toughs by your reply on my comment - was a bit late to the game). This rely on pow() , (and log10 for some nicety in print), tho so; if using gcc compile with -lm:
basemight be a bit confusing here - but guess you get the meaning.
gcc -Wall -Wextra -pedantic -o combo combo.c -lm
/* gcc - Wall -Wextra -pedantic -o combo combo.c -lm */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
static void prnt_combo(unsigned number, unsigned bits, int base)
{
if (!bits)
return;
prnt_combo(number / base, --bits, base);
printf("%d", number % base);
}
void prnt_combos(int bits, int base)
{
int i;
int n = pow(base, bits);
int wp = log10(n) + 1;
fprintf(stderr,
"Printing all combinations of 0 to %d by width of %d numbers. "
"Total %d.\n",
base - 1, bits, n
);
for (i = 0; i < n; i++) {
fprintf(stderr, "%*d : ", wp, i);
prnt_combo(i, bits, base);
printf("\n");
}
}
/* Usage: ./combo [<bits> [<base>]]
* Defaults to ./combo 3 2
* */
int main(int argc, char *argv[])
{
int bits = argc > 1 ? strtol(argv[1], NULL, 10) : 3;
int base = argc > 2 ? strtol(argv[2], NULL, 10) : 2;
prnt_combos(bits, base);
return 0;
}
Sample:
$ ./combo 4 2
Printing all combinations of 0 to 1 by width of 4 numbers. Total 16.
0 : 0000
1 : 0001
2 : 0010
3 : 0011
4 : 0100
5 : 0101
6 : 0110
7 : 0111
8 : 1000
9 : 1001
10 : 1010
11 : 1011
12 : 1100
13 : 1101
14 : 1110
15 : 1111
Or clean output:
$ ./combo 3 2 >&2-
000
001
010
011
100
101
110
111
You might like to add something like:
if (base > 10)
printf("%x", number % base);
else
printf("%d", number % base);
in prnt_combo(). This way you get i.e. by 2 16:
0 : 00
1 : 01
2 : 02
3 : 03
4 : 04
...
250 : fa
251 : fb
252 : fc
253 : fd
254 : fe
255 : ff
Related
I was practicing programming in C, and when I ran this code, it came to a point where the outputting numbers just gave up lol, it was around the 30th number of the sequence.
What is the limit to output numbers in C?
(I was trying the Fibonacci sequence)
int main() {
int fibo, i, n, a, aux;
printf("Enter a number: ");
scanf("%d", &fibo);
n = 1; a = 1;
printf("1 1 ");
for(i = 3; i <= fibo; i++){
/* aux = n;
n = n + a;
a = aux;*/
n += a;
a = n - a;
printf("%d ", n);
}
}
What is the limit to output numbers in C?
There is no such limit. You can create a library to do arithmetic operations on arbitrary large numbers - and output them.
The question should probably be "what ranges can the fundamental types in C represent?" - and there are different limits for the different fundamental types.
Here's an incomplete list of some types taken from limits.h:
INT_MIN - minimum value of int
INT_MAX - maximum value of int
LLONG_MIN - minimum value of long long int
LLONG_MAX - maximum value of long long int
And from float.h:
DBL_MIN - minimum, normalized, positive value of double (typically 0.)
-DBL_MAX - lowest finite value representable by double
DBL_MAX - maximum finite value of duuble
Note that
an int is required to be at least 16 bit wide, but is often 32.
a long int is required to be at least 32 bit wide and often is.
a long long int is required to be at least 64 bites wide.
Depending on the type's bit width and how the implementation make use of these bits (two's complement, ones' complement, sign–magnitude and for floating points, if they use IEEE 754 or something else) affects the ranges they can represent.
Fibonacci numbers get very large very quickly, and will exceed the range of native integer types for relatively small n. On my system, the largest Fibonacci number I can compute with the following code using a regular signed int is F(44):
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
int main( int argc, char **argv )
{
if ( argc < 2 )
{
fprintf( stderr, "USAGE: %s n\n", argv[0] );
exit( 0 );
}
int n = strtol( argv[1], NULL, 10 );
int f[3] = { 0, 1, 0 };
printf( "INT_MAX = %d\n", INT_MAX );
for ( int i = 1; i <= n && INT_MAX - f[2] > f[1] + f[0]; i++ )
{
f[2] = f[1] + f[0];
f[0] = f[1];
f[1] = f[2];
printf( "fib %3d = %10d\n", i, f[2] );
}
return 0;
}
Output:
$ ./fib 50
INT_MAX = 2147483647
fib 1 = 1
fib 2 = 2
fib 3 = 3
fib 4 = 5
fib 5 = 8
fib 6 = 13
fib 7 = 21
fib 8 = 34
fib 9 = 55
fib 10 = 89
fib 11 = 144
fib 12 = 233
fib 13 = 377
fib 14 = 610
fib 15 = 987
fib 16 = 1597
fib 17 = 2584
fib 18 = 4181
fib 19 = 6765
fib 20 = 10946
fib 21 = 17711
fib 22 = 28657
fib 23 = 46368
fib 24 = 75025
fib 25 = 121393
fib 26 = 196418
fib 27 = 317811
fib 28 = 514229
fib 29 = 832040
fib 30 = 1346269
fib 31 = 2178309
fib 32 = 3524578
fib 33 = 5702887
fib 34 = 9227465
fib 35 = 14930352
fib 36 = 24157817
fib 37 = 39088169
fib 38 = 63245986
fib 39 = 102334155
fib 40 = 165580141
fib 41 = 267914296
fib 42 = 433494437
fib 43 = 701408733
fib 44 = 1134903170
If I switch to unsigned int, I can compute up to F(45). If I use long, I can get up to F(90). But even if I use unsigned long long, I'll still exceed its range with relatively small n.
To compute Fibonacci sequences for arbitrarily large n, you'll need a third-party bignum library like GMP:
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <gmp.h>
int main( int argc, char **argv )
{
if ( argc < 2 )
{
fprintf( stderr, "USAGE: %s n\n", argv[0] );
exit( 0 );
}
int n = strtol( argv[1], NULL, 10 );
mpz_t f[3];
mpz_init_set_str( f[0], "1", 10 );
mpz_init_set_str( f[1], "1", 10 );
for ( int i = 1; i <= n; i++ )
{
mpz_add( f[2], f[1], f[0] );
mpz_set( f[0], f[1] );
mpz_set( f[1], f[2] );
gmp_printf( "fib %d = %Zd\n", i, f[2] );
}
return 0;
}
For n == 1000, I get
fib 1000 = 113796925398360272257523782552224175572745930353730513145086634176691092536145985470146129334641866902783673042322088625863396052888690096969577173696370562180400527049497109023054114771394568040040412172632376
Edit
Gah, the sequence starts off wrong - it should be 1, 1, 2, .... But my main point remains.
I want to add a value (potentially larger than 255) to an array of uint8_t. Currently, my implementation does not allow to exceed 255 as the value is of type uint8_t. Ideally I would like to have this value of type int.
This code must be compilable with standard libraries and be exclusively in C99. I don't have access to uint32_t or uint_64t types either.
How could I modify the following snippet to change value from uint8t to int ?
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
void addArray(uint8_t *dest, size_t sizeDest, uint8_t value){
uint8_t remaining = value;
uint8_t sum;
for (size_t i = 0; i < sizeDest; ++i){
sum = dest[i] + remaining;
if (dest[i] > sum){
remaining -= UINT8_MAX - (dest[i] - sum);
dest[i]=sum;
}
else{
dest[i]=sum;
return;
}
}
}
void printArray(uint8_t *t, size_t arrayLength){
for (int i = 0; i < arrayLength; ++i)
{
printf("%d ", t[i]);
}
printf("\n");
}
int main() {
printf("Max value of uint8_t is %d\n",UINT8_MAX);
int arrayLength = 16;
uint8_t key[] = {
252,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,2
};
uint8_t *testArray = (uint8_t *) malloc(sizeof(uint8_t) * arrayLength);
memcpy(testArray, key, sizeof(uint8_t)*arrayLength);
printf("Before addition\n");
printArray(testArray, arrayLength);
addArray(testArray,arrayLength,15);
printf("After addition\n");
printArray(testArray, arrayLength);
return 0;
}
You say you're not allowed to use uint32_t or uint64_t, but you are allowed to use int. If so, this is simple enough. Just use int to pass in your new value and to keep track of the partial, running sum.
I did it like this; it's quite similar to the code #chux posted. I also simplified the logic: you don't actually need to keep separate sum and remaining values, so I boiled it down to just one variable, which I'm calling carry, of type int.
void addArray(uint8_t *dest, size_t sizeDest, int value){
int carry = value;
for (size_t i = 0; i < sizeDest; ++i){
carry = dest[i] + carry;
dest[i] = carry & 0xff;
carry >>= 8;
}
}
During each trip through the loop, carry is either the value we're adding in, or the carry that's leftover from the previous "digit". We add the carry to the current digit, stash as much of it as will fit — the low-order 8 bits — back into the current digit, and keep what's leftover (that is, after using >>= to discard the low-order 8 bits, which are they ones we've just stored in dest[i]) in the carry variable for next time.
Why does this work? Well, it's the same thing you do when you add a column of numbers by hand, using the technique we all learned back in elementary school. Suppose you're adding
6
14
7
23
13
+ 4
----
After you add up the one's column, you get 27, and you say, "okay, that's 7, carry the 2". (You do not say, "carry the 20".) Your partial sum was 27, and the "bottom half" of it (7, or 27 % 10) is the digit in the one's place of the final sum, and the "top half" (2, or 27 / 10) is the carry into the ten's column.
So if you're not familiar or not comfortable with those "bitwise" operators, you can perform the equivalent operations using % and /, except using factors of 256 instead of 10:
void addArray(uint8_t *dest, size_t sizeDest, int value){
int carry = value;
for (size_t i = 0; i < sizeDest; ++i){
carry = dest[i] + carry;
dest[i] = carry % 256;
carry /= 256;
}
}
Basically you're performing addition here in base 256.
Depending on your needs and constraints, there might be some value in using types int16_t, unsigned int, or uint16_t for value and carry, instead of plain int.
I tested this by calling
addArray(testArray,arrayLength,300);
and it printed
Before addition
252 255 255 255 255 255 255 255 255 255 255 255 255 255 255 2
After addition
40 1 0 0 0 0 0 0 0 0 0 0 0 0 0 3
which looks right. As a second test,
addArray(testArray,arrayLength,123456789);
prints
After addition
17 205 91 7 0 0 0 0 0 0 0 0 0 0 0 3
(More on these tests in the "addendum" below.)
As #chux points out in a comment, this code does have its limitations. If the value you tried to add in was close to the maximum an int can hold, the carry variable might overflow (that is, on the carry = dest[i] + carry line). But as long as value is less than or equal to INT_MAX - 255 (and greater than or equal to zero!), you should be fine.
Of course, if the value you're trying to add in might be large, it might also be larger than a single int can hold, in which case you'd need to pass it in some other way, likely as a second array of uint8_t, just like dest — and then you'd find yourself writing a fully general multiprecision adder.
Addendum: To double-check these results, and to demonstrate what's actually going on, we can perform the same arithmetic in dc, the Unix/Linux arbitrary-precision calculator. I have determined that #Tifa's initial key value is 3987683987354747618711421180841033724. We'll use dc to print that number out in various bases, and as we add 15, 300, and 123456789 to it.
$ dc
3987683987354747618711421180841033724 # original key
p # print it
3987683987354747618711421180841033724
16o p # set output base to 16 and print
2FFFFFFFFFFFFFFFFFFFFFFFFFFFFFC
256o p # set output base to 256 and print
002 255 255 255 255 255 255 255 255 255 255 255 255 255 255 252
15 + p # add 15 and print (still base 256)
003 000 000 000 000 000 000 000 000 000 000 000 000 000 000 011
3987683987354747618711421180841033724 # original key again
300 + p # add 300 and print
003 000 000 000 000 000 000 000 000 000 000 000 000 000 001 040
3987683987354747618711421180841033724 # original key again
123456789 + p # add and print
003 000 000 000 000 000 000 000 000 000 000 000 007 091 205 017
dc's base-256 rendition corresponds to the output of Tifa's printArray function, albeit in a more conventional left-to-right order.
How to add a value greater than 255 to an array of uint_8t?
" Ideally I would like to have this value of type int. " --> As the goal is "a value greater than 255", we can simplify and use unsigned.
Add the unsigned to the uint8_t indexed in the array. As overflow may occur, use wider than unsigned math.
// Return overflow amount
// void addArray(uint8_t *dest, size_t sizeDest, uint8_t value){
unsigned addArray(uint8_t *dest, size_t sizeDest, unsigned value){
unsigned long long sum = value; // Use some type wider than unsigned
for (size_t i = 0; i < sizeDest; ++i) {
sum += dest[i];
dest[i] = (uint8_t) sum; // Save 8 lower bits
sum >>= 8; // Continue with the upper bits
}
return (unsigned) sum;
}
... or more like OP's code with no wider integer math used.
unsigned addArray(uint8_t *dest, size_t sizeDest, unsigned value){
#define UINT_MAX_PLUS1_DIV256 ((UINT_MAX - UINT_MAX/2) >> 7)
unsigned remaining = value;
for (size_t i = 0; i < sizeDest; ++i) {
unsigned sum = remaining + dest[i];
dest[i] = sum; // Save lower bits
if (sum < remaining) { // Overflow occurred in remaining + dest[i]
remaining = sum >> 8;
remaining += UINT_MAX_PLUS1_DIV256 // add back overflow bit / 256
} else{
remaining = sum >> 8; // Continue with the upper bits
}
}
return remaining
}
I am basically trying to convert a char vector to int values: in file stage_03.txt I have something like 10011 10101 10011 11001 etc. and the stage_04.txt file should look like 19 21 19 etc. This code works perfectly fine in Code::Blocks. However, the stage_04.txt file is totally messed up when I run the code in Linux terminal: ^R ^S ^D etc.
#include <stdio.h>
#include <math.h>
int main(void) {
char x[256];
int aux[1000];
int numar = 0;
int z = 0;
int i = 0;
int l = 0;
int ch;
FILE *fin = fopen("stage_03.txt", "r");
FILE *fout = fopen("stage_04.txt", "w");
while ((ch = fgetc(fin)) != EOF) {
x[i++] = ch;
}
for (int i = 0; i < l; i = i + 6) {
numar = 0;
for (int j = 0; j <= 4; j++)
numar = numar + (x[i + j] - '0') * pow(2, (4 - j));
aux[z++] = numar;
}
for (i = 0; i < z - 1; i++) {
fputc(aux[i], fout);
fputc(' ', fout);
}
return 0;
}
What can I do to solve this?
Here is my solution. Please do not regard this as a "final" code. In final code one should divide the code into subprocedures and add error handling. I left this out for simplicity, here. The solution adds more flexibility concerning the separators and lengths of the numbers in the source file.
It can easily deal with source files such as:
0 1 00 01 10 11 000 001 010 011
100 101 110 111
0000 0001 0010 0011 0100 0101
0110 0111 1000 1001 1010 1011 1100 1101 1110
1111 10011 11001
You can see that fields do not need to have a fixed size of 6 character like in the original code.
#include <stdio.h>
#include <math.h>
#include <string.h>
int main(void) {
char sourceValues[256];
int targetValues[1000];
int number = 0;
int numLength = 0;
int i = 0;
int charsToProcess = 0;
int ch;
const char *srcPtr = &sourceValues[0];
int* targetPtr = &targetValues[0];
FILE *fin = fopen("stage_03.txt", "r");
FILE *fout = fopen("stage_04.txt", "w");
// read source file and determine number of chars to be processed
while ((ch = fgetc(fin)) != EOF) {
sourceValues[i++] = ch;
}
sourceValues[i] = '\0'; // terminate source data
charsToProcess = i;
srcPtr += strcspn(srcPtr, "01"); // eventually skip leading whitespace
do {
numLength = strcspn(srcPtr, " \t\n\r\v"); // determine runlength until next separator
// Convert ASCII into binary form
number = 0;
for (int i = 0; i < numLength; ++i)
{
number <<= 1; // Make room for next digit and propagate existing digits stepwise to their final place
number += (*srcPtr++ == '1'); // Insert new digit at starting pos
}
*targetPtr++ = number; // Store converted number in binary representation in target array
srcPtr += strcspn(srcPtr, "01"); // Skip whitespace. Set srcPtr to next numeric sequence
} while (srcPtr < sourceValues + charsToProcess);
for (const int *ptr = &targetValues[0]; ptr < targetPtr; ++ptr) {
fprintf(fout, "%d ", *ptr);
}
return 0;
}
Here is the output to the input given above:
0 1 0 1 2 3 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 19 25
I need to iterate over an array of n elements (dynamic size thus), for example 4, as if it were a binary number, starting with all zeros ({0,0,0,0}). Every time this needs to increment as if it is binary, {0,0,0,0} -> {0,0,0,1} -> {0,0,1,0} -> {0,0,1,1} -> {0,1,0,0}, etc...
I have trouble generating an algorithm that does so with array values, I thought about using recursion but cannot find the method to do so other than hard-coding in ifs. I suppose I could generate an n-digit number and then apply any algorithm discussed in this post, but that would be inelegant; the OP asked to print n-digit numbers while I need to work with arrays.
It would be great if someone could point me in the right direction.
Context:
int n;
scans("%d", &n);
int *arr = calloc(n, sizeof(int));
Algorithm:
Start at the rightmost element.
If it's a zero, then set it to one and exit
It must be a one; set it to zero
If you are at the left-most element, then exit.
You aren't already at the left-most element; move left one element and repeat.
I'm sorry, I'm not in a position to provide a code sample.
Algorithm:
Start at the rightmost element.
If it's a zero, then set it to one and exit
It must be a one; set it to zero
If you are at the left-most element, then exit.
You aren't already at the left-most element; move left one element and repeat.
Here's Hymie's algorithm, I'll try making a code out of it :
#include <stdlib.h>
#include <stdio.h>
int my_algo(int *arr, int size) {
for (int i = size - 1; i >= 0; i--) { // Start at the rightmost element
if (arr[i] == 0) { // If it's a zero, then set it to one and exit
arr[i] = 1;
return 1;
} else if (arr[i] == 1) { // If it's a one, set it to zero and continue
arr[i] = 0;
}
}
return 0; // stop the algo if you're at the left-most element
}
int main() {
int n;
scanf("%d", &n);
int *arr = calloc(n, sizeof(int));
do {
for (int i = 0; i < n; i++) {
putchar(arr[i] + '0');
}
putchar('\n');
} while (my_algo(arr, n));
return (0);
}
This algorithm is dynamic and work with scanf.
Here's the result for 4 :
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
What you seem to want to do is implement binary addition (or more precisely a binary counter), which is anyway implemented in the CPU's digital circuit using logic gates. It can be done using combination of logical operations (nand and xor to be exact).
But the most elegant approach according to my sense of elegance would be to use the CPU's innate ability to increment numbers and write a function to decompose a number to a bit array:
void generate_bit_array(unsigned int value, uint8_t *bit_array, unsigned int bit_count) {
for (unsigned int i=0; i<bit_count; i++) {
bit_array[i] = value >> (bit_count - i - 1) & 0x01;
}
}
int main(int argc, void **argv) {
unsigned int i;
uint8_t my_array[4];
/* Iterate and regenerate array's content */
for (i=0; i<4; i++) {
generate_bit_array(i, my_array, 4);
/* Do something */
}
return 0;
}
You can do:
#include <stdio.h>
#include <stdlib.h>
void gen_bit_array(int *numarr, int n, int arr_size) {
if(n > 0) {
numarr[arr_size-n] = 0;
gen_bit_array(numarr, n-1, arr_size);
numarr[arr_size-n] = 1;
gen_bit_array(numarr, n-1, arr_size);
} else {
int i;
for(i=0; i<arr_size; i++)
printf("%d", numarr[i]);
printf ("\n");
}
}
int main() {
int n,i;
printf ("Enter array size:\n");
scanf("%d", &n);
int *numarr = calloc(n, sizeof(int));
if (numarr == NULL)
return -1;
gen_bit_array(numarr, n, n);
return 0;
}
Output:
Enter array size:
2
00
01
10
11
Enter array size:
4
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
If I have understood you correctly then what you need is something like the following
#include <stdio.h>
#define N 4
void next_value( unsigned int a[], size_t n )
{
unsigned int overflow = 1;
for ( size_t i = n; i != 0 && overflow; i-- )
{
overflow = ( a[i-1] ^= overflow ) == 0;
}
}
int empty( const unsigned int a[], size_t n )
{
while ( n && a[n-1] == 0 ) --n;
return n == 0;
}
int main(void)
{
unsigned int a[N] = { 0 };
do
{
for ( size_t i = 0; i < N; i++ ) printf( "%i ", a[i] );
putchar( '\n' );
next_value( a, N );
} while ( !empty( a, N ) );
return 0;
}
The program output is
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
Or you can write the function that evaluates a next value such a way that if the next value is equal to 0 then the function returns 0.
For example
#include <stdio.h>
#include <stdlib.h>
int next_value( unsigned int a[], size_t n )
{
unsigned int overflow = 1;
for ( ; n != 0 && overflow; n-- )
{
overflow = ( a[n-1] ^= overflow ) == 0;
}
return overflow == 0;
}
int main(void)
{
size_t n;
printf( "Enter the length of the binary number: " );
if ( scanf( "%zu", &n ) != 1 ) n = 0;
unsigned int *a = calloc( n, sizeof( unsigned int ) );
do
{
for ( size_t i = 0; i < n; i++ ) printf( "%i ", a[i] );
putchar( '\n' );
} while ( next_value( a, n ) );
free( a );
return 0;
}
The program output might look like
Enter the length of the binary number: 3
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
No need for an algorithm, you could build a function,
Here is a process which could be a good idea if the array is of a fixed size :
Build a function which take your array
Create a local integrer for this function
Set the bits value of the integrer to the cells value of the array
Increment the integrer
Set the array values to match each bits of the integrer
All this process can be done using shifts (>> <<) and masks (& 255 for example).
Hi i'm fairly new to c but for a program I'm writing I need to convert binary strings to decimal numbers. here is my current code:
int BinaryToInt(char *binaryString)
{
int decimal = 0;
int len = strlen(binaryString);
for(int i = 0; i < len; i++)
{
if(binaryString[i] == '1')
decimal += 2^((len - 1) - i);
printf("i is %i and dec is %i and the char is %c but the length is %i\n", i, decimal, binaryString[i], len);
}
return decimal;
}
int main(int argc, char **argv)
{
printf("%i", BinaryToInt("10000000"));
}
and here is the output:
i is 0 and dec is 5 and the char is 1 but the length is 8
i is 1 and dec is 5 and the char is 0 but the length is 8
i is 2 and dec is 5 and the char is 0 but the length is 8
i is 3 and dec is 5 and the char is 0 but the length is 8
i is 4 and dec is 5 and the char is 0 but the length is 8
i is 5 and dec is 5 and the char is 0 but the length is 8
i is 6 and dec is 5 and the char is 0 but the length is 8
i is 7 and dec is 5 and the char is 0 but the length is 8
5
I'm confused as to why this doesn't work, all help is greatly appreciated. Thanks in advance!
Ps: I'm used to java so at the moment C just makes me cry
The ^ operator is not for exponentiation, but is instead the bitwise XOR operator.
If you want to raise a number to a power of 2, use the left shift operator << to shift the value 1 by the exponent in question.
decimal += 1 << ((len - 1) - i);
The trick is the same as with any number base: for each incoming digit, multiply the accumulator by the number base and add the digit.
#include <stdio.h>
#include <string.h>
int BinaryToInt(char *binaryString)
{
int decimal = 0;
int len = strlen(binaryString);
for(int i = 0; i < len; i++) {
decimal = decimal * 2 + binaryString[i] - '0';
}
return decimal;
}
int main(void)
{
printf("%d", BinaryToInt("10000000"));
return 0;
}
Program output:
128