Represent Unsigned Integer in Binary - c

How can I represent an unsigned integer as Binary ?

To create a string representation of some integer value you can use the following code:
#include <stdlib.h>
int main(int argc, char *argv[]) {
int j;
unsigned int value = 1024+2048+4096; // some value
char mask[8*sizeof(unsigned int) + 1] = {0};
for (j = 0; j < (8*sizeof(unsigned int) + 1); j++) {
mask[j] = (value << j) & (1 << (8*sizeof(unsigned int)-1)) ? '1' : '0';
}
printf("value is b%s\n", mask);
return 0;
}

Try this:
#include<stdio.h>
int main(void) {
int a,i,k=1;
int arr[32]; \\ taken an array of size 32
for(i=0;i <32;i++)
{
arr[i] = 0; \\initialised array elements to zero
}
printf("enter a number\n");
scanf("%d",&a); \\get input from the user
for(i = 0;i < 32 ;i++)
{
if(a&k) \\bit wise and operation
{
arr[i]=1;
}
else
{
arr[i]=0;
}
k = k<<1; \\left shift by one place evry time
}
for(i = 31 ;i >= 0;i--)
{
printf("%d",arr[i]); \\print the array in reverse
}
return 0;
}

Related

How to concatenate bit by bit in c?

I have matrix of '1' and '0' with the dimensions 8x8. I need to store the whole matrix in one unsigned long long variable bit by bit. How can i do that?
For example, let's take the matrix of '1' and '0' that is 2x2:
The matrix 2x2:
1 0
0 1
The variable must contain: 1001 in bits.
The same example, but over the matrix 8x8 and unsigned long long variable.
That's what i've tried to do:
#include <stdio.h>
int main()
{
unsigned long long result = 0;
char matrix[8][8]; // lets that the matrix is already filled by '1' and '0'
for (i=0; i<SIZE; i++)
{
for (j=0; j<SIZE; j++)
{
result = result | ((unsigned long long)(matrix[i][j] - '0'));
result <<= 1;
}
}
return 0;
}
Is it right? I implemented this nested loop in my algorithm and that didn't work properly.
Converting the text representation of an integer into its integer value can be done using strtoull().
char buf[sizeof(matrix)+1];
memcpy(buf, matrix, sizeof(matrix));
buf[sizeof(matrix)] = '\0';
result = strtoull(buf, NULL, 2);
try this
const int mx_size = 8;
int main() {
unsigned long long result = 0;
bool matrix[8][8]; // lets that the matrix is already filled by '1' and '0'
for (int i =0; i < mx_size; ++i)
matrix[i][i] = 1;
for (int i = 0; i < mx_size; i++) {
for (int j = 0; j < mx_size; j++) {
result |= (unsigned long long)matrix[i][j] << (i*mx_size + j);
}
}
return 0;
}
Here you have the code (a bit more
#include <stdio.h>
#include <stdint.h>
uint64_t convert(char matrix[8][8], int order, char zero)
{
uint8_t byte;
uint64_t result = 0;
for(size_t row = 0; row < 8; row++)
{
byte = 0;
for(size_t column = 0; column < 8; column++)
{
byte <<= 1;
byte |= matrix[row][column] != zero ? 1 : 0; //anything != defined zero char is 1
}
if (order)
{
result |= (uint64_t)byte << (8 * row);
}
else
{
result |= (uint64_t)byte << (56 - 8 * row);
}
}
return result;
}
int main(void) {
char matrix[8][8] =
{
{'1','0','1','0','1','0','1','0'},
{'0','1','0','1','0','1','0','1'},
{'1','1','1','0','0','0','1','1'},
{'0','0','0','1','1','1','0','0'},
{'1','1','1','1','1','0','0','0'},
{'0','0','0','0','1','1','1','1'},
{'1','1','0','0','1','1','0','0'},
{'0','0','1','1','0','0','1','1'},
};
unsigned long long result = convert(matrix, 0, '0');
for(size_t index = 0; index < 64; index ++)
printf("%1d", !!(result & (1ULL << index)));
printf("\n");
result = convert(matrix,1, '0');
for(size_t index = 0; index < 64; index ++)
printf("%1d", !!(result & (1ULL << index)));
printf("\n");
return 0;
}

Representation of code (C)

Can you please help re-write this code. I am not able to understand how the bitwise leftshift actually works. If there is a easier way to represent this code then please let me know.
This code is to calculate the number of 1 (ones) in a bit representation of a number.
int numberofones( int value, int count) {
int numchars = 8 * sizeof(int);
int n;
for(n = 0; n < numchars; n++)
{
if(value & (1 << (numchars - 1 - n))) {
count++;
}
}
return count;
}
int numberofones( int value) {
int numchars = 8 * sizeof(int);
int n;
int count = 0 ;
for(n = 0; n < numchars; n++)
{
if(value & (1 << n))
count++;
}
return count;
}

Run-time error occurs when input value is greater than 100000

I am trying to implement the sieve of eratosthenes in C. The code works for small input values, but once the input goes beyond a certain range, a run- time error is thrown. This is the second problem in the classical section of the SPOJ base. What is the mistake?
#include<stdio.h>
#include<math.h>
int prime(unsigned long int, unsigned long int);
int main()
{
int nitem;
unsigned long int sn,fn;
scanf("%d", &nitem);
while(nitem)
{
scanf("%lu", &fn);
//printf("%d",fn);
scanf("%lu", &sn);
prime(fn, sn);
nitem--;
}
return 0;
}
int prime(unsigned long int fn, unsigned long int sn)
{
unsigned long int prim[100000];
int i,j,k;
for(i = 0; i < 100000; i++)
{
prim[i] = 1;
}
prim[0] = 0;
prim[1] = 0;
//printf("%d", sn);
//printf("%d", k);
//printf("%d", (k <= sn));
for(k = 2; k <= sqrt(sn); k++)
{
// printf("alksnc%5d", k);
if(prim[k] == 1)
{
for(j = 2; (k * j) <= sn; j++)
{
//printf("%d", prim[k]);
prim[k * j] = 0;
}
}
}
for(int i = 0; i <= sn; i++)
{
if(prim[i] !=0 && i >= fn)
{
printf("%lu\n", i);
}
}
printf("\n");
return;
}
Input:
1
100000 100345
output:
run time error
Input:
1
3 5
output:
3
5
We can make more efficient use of memory (2x) by only sieving odd numbers as all the even numbers you're processing waste time and space. It's trickier to work out but gives us something like:
#include <math.h>
#include <libc.h>
#define MAX_ODD_PRIMES 1048576
void prime(unsigned long fn, unsigned long sn)
{
unsigned char primes[MAX_ODD_PRIMES];
for (unsigned long i = 0; i < MAX_ODD_PRIMES; i++)
{
primes[i] = TRUE;
}
primes[0] = 0; // preset first odd, '1'
for (unsigned long k = 3; k <= sqrt(sn) + 1; k += 2)
{
if (primes[k / 2])
{
for (unsigned long j = 3; (k * j) <= sn; j += 2)
{
primes[k * j / 2] = FALSE;
}
}
}
if (fn <= 2)
{
printf("2\n");
fn = 3;
}
for (unsigned long i = fn / 2; i * 2 + 1 <= sn; i++)
{
if (primes[i])
{
printf("%lu\n", i * 2 + 1);
}
}
}
EXAMPLE
> ./a.out
1 1999900 2000000
1999957
1999969
1999979
1999993
>
1) Array range error.
By changing code
for (j = 2; (k * j) <= sn; j++) {
if (k * j >= 100000) {
printf("Out of range %d %d\n", k, j);
exit(1);
}
prim[k * j] = 0;
}
}
With input 2, 100000
Output
Out of range 2 50000
By using an array (VLA) sized to the task, this is avoided. Many other optimizations available. Consider also a malloc() array.
void prime(unsigned long int fn, unsigned long int sn) {
unsigned long int prim[sn + 1];
2) int prime() eventually performs return; where return something; is expected. Suggest changing function to void prime()
int prime(unsigned long int fn, unsigned long int sn) {
unsigned long int prim[100000];
...
printf("\n");
return;
}

Not reading anything past scanf()

I am new to C and wondering why I am not getting any kind of output. I am trying to get my program to convert a hexadecimal number to binary.
#include <stdio.h>
#include <stdlib.h>
int* hex2binary(int hex_array[], int input_array_size, int* return_array_size) {
int hex_size = input_array_size;
int binary_array_size = 4 * hex_size;
int *binary_array = (int*) malloc(binary_array_size * sizeof(int));
int hex_index, binary_index;
for (hex_index = 0; hex_index < hex_size; hex_index++) {
int hex_num = hex_array[hex_index];
binary_index = hex_index * 4;
int bit_count;
for (bit_count = 3; bit_count <= 0; bit_count--) {
binary_array[binary_index + bit_count] = hex_num % 2;
hex_num = hex_num / 2;
}
hex_index++;
}
*return_array_size = binary_array_size;
return binary_array;
}
int main() {
char baseString[11];
int count = 0;
int i, j;
int original, wanted;
int size;
printf("Welcome to use this number base converter program.\n");
printf("Please input the original base: ");
scanf("%d", &original);
printf("Please input a base-%d number with more more than 10 digits: ",
original);
scanf("%s", baseString);
while (baseString[count] != '\0')
count++;
int *baseNumber = (int*) malloc(count * sizeof(int));
for (i = 0; i < count; i++) {
baseNumber[i] =
baseString[i] <= '9' ? baseString[i] - '0' : baseString[i] - 'A' + 10;
}
int* result_array;
printf("Please input the target base: ");
scanf("%d", &wanted); //doesn't read anything past this point
printf("Target base: %d", wanted);
if (original == 16) {
if (wanted == 2) {
result_array = hex2binary(baseNumber, count, size);
for (j = 0; j < size; j++) {
printf("Result: %d", result_array[j]);
}
}
}
}
I know it can't be something to difficult, but I can't seem to figure out why it isn't even producing some kind of output.
This line
result_array = hex2binary(baseNumber, count, size);
is incorrect because this function needs a pointer argument
int* hex2binary(int hex_array[], int input_array_size, int* return_array_size)
So it should be called like this
result_array = hex2binary(baseNumber, count, &size); // note the &
Then the subsequent loop
for (j = 0; j < size; j++)
will no longer be using the uninitialised variable size.

Generate all binary strings of length n with k bits set.(need to write on C)

Please help me to solve this task:
Generate all binary strings of length n with k bits set.(need to write on C)
for example:
n=5
k=3
11100
00111
11010
01011
**01110
11001
10011
**01101
**10110
10101
** can't generate these permutations
Code:
#include <stdio.h>
#define N 10
int main (void)
{
int mas[N]={0},kst,m,n1,z,a,b;
printf("\n\nVvedit` rozmirnist` masyvu: ");
scanf("%d",&kst);
printf("\n\nVvedit` kil`kist` odynyc`: ");
scanf("%d",&n1);
for(m=0;m1;m++)
mas[m]=1;
for(m=0;m<kst;m++)
printf("%d",mas[m]);
printf("\n");
for(m=0;m<n1;m++){
for(z=0;z<(kst-1);z++)
if((mas[z]==1) && (mas[z+1]==0)){
a=mas[z];
mas[z]=mas[z+1];
mas[z+1]=a;
for(b=0;b<kst;b++)
printf("%d",mas[b]);
printf("\n");
}
}
return 0;
}
I have solved this problem earlier! please find my code below! I hope this will help you out.
#include<stdio.h>
int NumberOfBitsSet(int number)
{
int BitsSet = 0;
while(number != 0)
{
if(number & 0x01)
{
BitsSet++;
}
number = number >> 1;
}
return BitsSet;
}
void PrintNumberInBinary(int number, int NumBits)
{
int val;
val = 1 << NumBits; // here val is the maximum possible number of N bits with only MSB set
while(val != 0)
{
if(number & val)
{
printf("1");
}
else
{
printf("0");
}
val = val >> 1;
}
}
int main()
{
int n,k,i;
int max,min;
printf("enter total number of bits and number of bits to be set:\n");
scanf("%d %d", &n, &k);
min = ((1 << k) - 1); //min possible values with k bits set
max = (min << (n-k)); //max possible value with k bits set!
//printf("%d %d", min, max);
for(i=0; i<= max; i++)
{
if(!(i<min))
{
if(NumberOfBitsSet(i) == k)
{
PrintNumberInBinary(i, (n-1));
printf("\n");
}
}
}
return 0;
}
Your code is a mess ;)
Seriously: first rule when solving a task in code is to write clean code, use sensible variable naming etc.
For tasks like this one I would suggest using this.
Now to your sample code: it would not compile and it is hard to read what you are trying to do. Formatted and with some comments:
#include <stdio.h>
#define N 10
int main(void)
{
int mas[N] = {0};
int kst, m, n1, z, a, b;
/* Read width ? */
printf("\n\nVvedit` rozmirnist` masyvu: ");
scanf("%d", &kst);
/* Read number of bit's set? */
printf("\n\nVvedit` kil`kist` odynyc`: ");
scanf("%d", &n1);
/* m1 is not defined, thus the loop give no meaning.
* Guess you are trying to set "bits" integers to 1.
*/
for (m = 0; m1; m++)
mas[m] = 1;
/* This should be in a function as 1. You do it more then once, and
* 2. It makes the code much cleaner and easy to maintain.
*/
for (m = 0; m < kst; m++)
printf("%d", mas[m]);
printf("\n");
for (m = 0; m < n1; m++) {
for (z = 0; z < (kst - 1); z++) {
if ((mas[z] == 1) && (mas[z + 1] == 0)) {
a = mas[z]; /* Same as a = 1; */
mas[z] = mas[z + 1]; /* Same as mas[z] = 0; */
mas[z + 1] = a; /* Same as mas[z + 1] = 1; */
/* Put this into a function. */
for (b = 0; b < kst; b++)
printf("%d", mas[b]);
printf("\n");
}
}
}
return 0;
}
The extensive use of printf when one are not sure of what is going on is a precious tool.
This is not a solution, (it is basically doing the same as your post, but split up), but a sample of something that might be easier to work with. I have also used a char array as C-string instead of integer array. Easier to work with in this situation.
If you want to use integer array I'd suggest you add a print_perm(int *perm, int width) helper function to get it out of the main code.
#include <stdio.h>
#define MAX_WIDTH 10
int get_spec(int *width, int *bits)
{
fprintf(stderr, "Enter width (max %-2d): ", MAX_WIDTH);
scanf("%d", width);
if (*width > MAX_WIDTH) {
fprintf(stderr, "Bad input: %d > %d\n", *width, MAX_WIDTH);
return 1;
}
fprintf(stderr, "Enter set bits (max %-2d): ", *width);
scanf("%d", bits);
if (*bits > MAX_WIDTH) {
fprintf(stderr, "Bad input: %d > %d\n", *bits, MAX_WIDTH);
return 1;
}
return 0;
}
void permutate(int width, int bits)
{
char perm[MAX_WIDTH + 1];
int i, j;
/* Set "bits" */
for (i = 0; i < width; ++i)
perm[i] = i < bits ? '1' : '0';
/* Terminate C string */
perm[i] = '\0';
fprintf(stderr, "\nPermutations:\n");
printf("%s\n", perm);
for (i = 0; i < bits; ++i) {
/* Debug print current perm and outer iteration number */
printf("%*s LOOP(%d) %s\n",
width, "", i, perm
);
for (j = 0; j < (width - 1); ++j) {
if (perm[j] == '1' && perm[j + 1] == '0') {
perm[j] = '0';
perm[j + 1] = '1';
printf("%s j=%d print\n",
perm, j
);
} else {
/* Debug print */
printf("%*s j=%d skip %s\n",
width, "", j, perm
);
}
}
}
}
int main(void)
{
int width, bits;
if (get_spec(&width, &bits))
return 1;
permutate(width, bits);
return 0;
}
If you want to list all of the permutations uniquely without doing "iterate and check", you can do something like this:
# Move peg x up m using s
# x is negative
# m is positive
def move(x, m, s):
for i in range(1, m+1):
s2 = list(s)
s2[x] = 0
s2[x - i] = 1
print(s2)
if x + 1 < 0:
move(x+1, i, s2)
# Print all unique permutations of
# n bits with k ones (and n-k zeros)
def uniqPerms(n, k):
s = [0 for _ in range(n-k)] + [1 for _ in range(k)]
print(s)
move(-k, n-k, s)
if __name__ == '__main__':
from sys import argv
uniqPerms(int(argv[1]), int(argv[2]))
The idea is that you inch the 1's up recursively, so that each movement produces a unique list (since a 1 is now somewhere none was before).
And you said it must be in C:
#include <stdio.h>
#include <stdlib.h>
enum { n = 8 };
struct string
{
char str[n + 1];
};
void move(int x, int m, string s)
{
for (int i = 0; i <= m; ++i)
{
string s2 = s;
s2.str[n + x] = '0';
s2.str[n + x - i] = '1';
printf("%s\n", s2.str);
if (x + 1 < 0)
move(x + 1, i, s2);
}
}
void uniqPerms(int k)
{
string s;
for (int i = 0; i < n - k; ++i)
s.str[i] = '0';
for (int i = n - k; i < n; ++i)
s.str[i] = '1';
s.str[n] = '\0';
printf("%s\n", s.str);
move(-k, n - k, s);
}
int main(int argc, char *argv[])
{
uniqPerms(atoi(argv[1]));
return 0;
}
try this
A[n-1]=0;
func(n-1);
A[n-1]=1;
func(n-1);
//Think simple people but please bear with me i love java
//Assume array A is globally defined
void Binary(int n)
{
if(n<1)
{
System.out.println(A);
}
else
{
A[n-1]=0;
Binary(n-1);
A[n-1]=1;
Binary(n-1);
}
}
here is the recursive solution
#include <iostream>
#include <vector>
using namespace std;
char v[4];
int count = 0;
void printString(){
int i;
for(i = 0; i < 4; i++){
cout << v[i] << " ";
}
cout <<count << endl;
}
void binary(int n){
if(n < 0){
if(count == 2)
printString();
}
else{
v[n] = '0';
binary(n - 1);
v[n] = '1';
count++;
binary(n-1);
count--;
}
}
int main(){
binary(3);
return 0;
}
#include<stdio.h>
int main(){
int n,k,i,j,a[50];
//lets suppose maximum size is 50
printf("Enter the value for n");
scanf("%d",&n);
printf("Enter the value for k");
scanf("%d",&k);
//create an initial bitstring of k 1's and n-k 0's;
for(i=0;i<n;i++){
if(k>0)
a[i]=1;
else
a[i]=0;
k--;
}
for(i=0;i<n;i++){
if(a[i]==1){
for(j=0;j<n;j++){
if(j!=i&&a[j]==0){
a[j]=1;a[i]=0;
for(k=0;k<n;k++){printf("%d\n",a[k]);}
a[i]=1; a[j]=0;
}}}}
return 0;
}
**If Complexity doesn't matter you can use the following code which are done in java. which will provide the desired output in o(2^n).Here I have find all the combination of 0 and 1 for the given n bits in array of size n.In case of K bit is set I have counted the number of 1 presented is equal to k using countBits() funtion.if so I have printed that array.
public class GenerateAllStringOfNBitsWithKBitsSet {
public static int a[] ={0,0,0,0,0};
static int k=3;
public static boolean countBits(){
int y=0;
for(int i=0;i<a.length;i++)
y += a[i] & 1 ;
if(y==k)
return true;
return false;
}
public static void gen(int n)
{
if(n<1)
{
if(countBits())
System.out.println(Arrays.toString(a));
}
else
{
a[n-1]=0;
gen(n-1);
a[n-1]=1;
gen(n-1);
}
}
public static void main(String[] args) {
GenerateAllStringOfNBitsWithKBitsSet.gen(a.length);
}
}

Resources