Cannot print out Binary calculation - c

I have a skeleton code to take the inputs of two numbers and add them together, however i don't know how to write out the part of the code to convert the inputs into a binary number
for example, if i type ./calc.c 5+5. The number is 10 and the binary is 00001010.
But i don't know how to convert the decimal into binary using code.
Any help?
Thanks.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char ** argv){
int dec1 = atoi(argv[1]);
char op = argv[2][0];
int dec2 = atoi(argv[3]);
int i;
printf("Called with dec1: %d op: %c dec2: %d\n", dec1, op, dec2);
if(dec1 & 1){
printf("bit is 1\n");
}
int sum = dec1 + dec2;
if (op == '+'){
for (i=0; i < 4; i++){
printf("%d\n", i);
}
}
printf("\n");
return 0;
}

One solution is to check the value of each individual bit with a bitmask. Note that an integer is generally 4 bytes on most systems, but for the sake of your example let's only consider the rightmost 8 bits. Also, I'm going to assume that sum is already correctly calculated since your question is about printing an integer in binary and not parsing equations or arithmetic.
Let's make a bitmask equivalent to 10000000, which equals 128, and then rotate it. Then we can check sum with a bitwise AND to see if each bit is set.
int bitmask = 128;
for (int i = 0; i < 8; i++ ) {
if (sum & bitmask)
printf("1");
else
printf("0");
bitmask = bitmask >> 1;
}
printf("\n");
This solution checks each bit in sum, left to right, to see if it is set. If so, print a 1, otherwise, print 0. This is one way to print integers in binary.

Related

C: get the bits of an integer

I have a program that will take two 4-byte integers as input and I need to store these into integer arrays like so...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[]) {
int vals1[32], vals2[32];
int num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);
// so argv[1] might be 47 and I would want to set the values of the vals1 array to reflect that in binary form
}
Any suggestions?
First task would be to convert a char * to an int, which you said you can. So here comes the next part i.e. getting the binary representation. For getting the binary representation of any data type, usage of Shift Operator is one of the best ways. And you can get it by performing shift on the data type and then performing Bitwise AND i.e. & with 1. For example, if n is an integer
int n = 47;
for (int i = 0; i < 32; i++)
{
/* It's going to print the values of bits starting from least significant. */
printf("Bit%d = %d\r\n", i, (unsigned int)((n >> i) & 1));
}
So, using shift operator, solution to your problem would be something like
void fun(int n1, int n2)
{
int i, argv1[32], argv2[32];
for (i = 0; i < 32; i++)
{
argv1[i] = ((unsigned int)n1 >> i) & 1;
argv2[i] = ((unsigned int)n2 >> i) & 1;
}
}
You have to be careful about the bit order i.e. which bit are being stored at which of the array index.

Long Long Decimal Binary Representation using C

I've been trying to print out the Binary representation of a long long integer using C Programming
My code is
#include<stdio.h>
#include <stdlib.h>
#include<limits.h>
int main()
{
long long number, binaryRepresentation = 0, baseOfOne = 1, remainder;
scanf("%lld", &number);
while(number > 0) {
remainder = number % 2;
binaryRepresentation = binaryRepresentation + remainder * baseOfOne;
baseOfOne *= 10;
number = number / 2;
}
printf("%lld\n", binaryRepresentation);
}
The above code works fine when I provide an input of 5 and fails when the number is 9223372036854775807 (0x7FFFFFFFFFFFFFFF).
1.Test Case
5
101
2.Test Case
9223372036854775807
-1024819115206086201
Using a denary number to represent binary digits never ends particularly well: you'll be vulnerable to overflow for a surprisingly small input, and all subsequent arithmetic operations will be meaningless.
Another approach is to print the numbers out as you go, but using a recursive technique so you print the numbers in the reverse order to which they are processed:
#include <stdio.h>
unsigned long long output(unsigned long long n)
{
unsigned long long m = n ? output(n / 2) : 0;
printf("%d", (int)(n % 2));
return m;
}
int main()
{
unsigned long long number = 9223372036854775807;
output(number);
printf("\n");
}
Output:
0111111111111111111111111111111111111111111111111111111111111111
I've also changed the type to unsigned long long which has a better defined bit pattern, and % does strange things for negative numbers anyway.
Really though, all I'm doing here is abusing the stack as a way of storing what is really an array of zeros and ones.
As Bathsheba's answer states, you need more space than is
available if you use a decimal number to represent a bit sequence like that.
Since you intend to print the result, it's best to do that one bit at a time. We can do this by creating a mask with only the highest bit set. The magic to create this for any type is to complement a zero of that type to get an "all ones" number; we then subtract half of that (i.e. 1111.... - 0111....) to get only a single bit. We can then shift it rightwards along the number to determine the state of each bit in turn.
Here's a re-worked version using that logic, with the following other changes:
I use a separate function, returning (like printf) the number of characters printed.
I accept an unsigned value, as we were ignoring negative values anyway.
I process arguments from the command line - I tend to find that more convenient that having to type stuff on stdin.
#include <stdio.h>
#include <stdlib.h>
int print_binary(unsigned long long n)
{
int printed = 0;
/* ~ZERO - ~ZERO/2 is the value 1000... of ZERO's type */
for (unsigned long long mask = ~0ull - ~0ull/2; mask; mask /= 2) {
if (putc(n & mask ? '1' : '0', stdout) < 0)
return EOF;
else
++printed;
}
return printed;
}
int main(int argc, char **argv)
{
for (int i = 1; i < argc; ++i) {
print_binary(strtoull(argv[i], 0, 10));
puts("");
}
}
Exercises for the reader:
Avoid printing leading zeros (hint: either keep a boolean flag that indicates you've seen the first 1, or have a separate loop to shift the mask before printing). Don't forget to check that print_binary(0) still produces output!
Check for errors when using strtoull to convert the input values from decimal strings.
Adapt the function to write to a character array instead of stdout.
Just to spell out some of the comments, the simplest thing to do is use a char array to hold the binary digits. Also, when dealing with bits, the bit-wise operators are a little more clear. Otherwise, I've kept your basic code structure.
int main()
{
char bits[64];
int i = 0;
unsigned long long number; // note the "unsigned" type here which makes more sense
scanf("%lld", &number);
while (number > 0) {
bits[i++] = number & 1; // get the current bit
number >>= 1; // shift number right by 1 bit (divide by 2)
}
if ( i == 0 ) // The original number was 0!
printf("0");
for ( ; i > 0; i-- )
printf("%d", bits[i]); // or... putchar('0' + bits[i])
printf("\n");
}
I am not sure what you really want to achieve, but here is some code that prints the binary representation of a number (change the typedef to the integral type you want):
typedef int shift_t;
#define NBITS (sizeof(shift_t)*8)
void printnum(shift_t num, int nbits)
{
int k= (num&(1LL<<nbits))?1:0;
printf("%d",k);
if (nbits) printnum(num,nbits-1);
}
void test(void)
{
shift_t l;
l= -1;
printnum(l,NBITS-1);
printf("\n");
l= (1<<(NBITS-2));
printnum(l,NBITS-1);
printf("\n");
l= 5;
printnum(l,NBITS-1);
printf("\n");
}
If you don't mind to print the digits separately, you could use the following approach:
#include<stdio.h>
#include <stdlib.h>
#include<limits.h>
void bindigit(long long num);
int main()
{
long long number, binaryRepresentation = 0, baseOfOne = 1, remainder;
scanf("%lld", &number);
bindigit(number);
printf("\n");
}
void bindigit(long long num) {
int remainder;
if (num < 2LL) {
printf("%d",(int)num);
} else {
remainder = num % 2;
bindigit(num/2);
printf("%d",remainder);
}
}
Finally I tried a code myself with idea from your codes which worked,
#include<stdio.h>
#include<stdlib.h>
int main() {
unsigned long long number;
int binaryRepresentation[70], remainder, counter, count = 0;
scanf("%llu", &number);
while(number > 0) {
remainder = number % 2;
binaryRepresentation[count++] = remainder;
number = number / 2;
}
for(counter = count-1; counter >= 0; counter--) {
printf("%d", binaryRepresentation[counter]);
}
}

Simple C function returns nonsense

I need to make simple function that converts binary number (string) to decimal number (long). When it returns result, it's nonsense. I've tried to return all others variables and it returned correct numbers. There is something wrong with my result variable.
#include "stdio.h"
#include "string.h"
#include "math.h"
long bintodec(const char *bin_num) {
long DIGIT, SUBTOTAL, RESULT = 0, I, LEN;
LEN = strlen(bin_num);
for(I = 0; I != LEN; I++) {
sscanf(&bin_num[I], "%li", &DIGIT);
SUBTOTAL = DIGIT * pow(2, LEN - I - 1);
RESULT = RESULT + SUBTOTAL;
}
return RESULT;
}
main() {
clrscr();
printf("%li", bintodec("101"));
getch();
}
sscanf is expecting a C string:
During the first iteration it receives "101" and 101 * 4 is 404
During the second iteration it receives 01 and 1 * 2 is 2
During the third iteration it receives 1 and 1 * 1 is 1
404 + 2 + 1 is 407 which must be the nonsense you are seeing
What you want is to convert each character:
DIGIT = bin_num[I] - '0';
You can convert string to long in one go, no need to iterate in loop. Changing your code like below can give you desired output
#include <stdio.h>
#include <string.h>
#include <math.h>
long bintodec(const char *bin_num)
{
long DIGIT, SUBTOTAL, RESULT = 0, I, LEN, REM;
LEN = strlen(bin_num);
sscanf(bin_num, "%li", &DIGIT);
printf("DIGIT = %li\n", DIGIT);
for (I = 0; I < LEN; I++)
{
REM = DIGIT%10;
RESULT += REM * pow(2, I);
DIGIT /= 10;
}
return RESULT;
}
int main() {
printf("%li", bintodec("101"));
}
Rather than debug your code, I'll present a more elegant solution. Consider:
long bintodec(const char *bin_num)
{
long sum = 0;
for (; *bin_num != '\0'; bin_num++) /* move pointer through string */
{
sum <<= 1; /* shift bits left (meaningless on first pass) */
sum |= (*bin_num == '1'); /* conditionally tack on new least significant bit */
}
return sum;
}
Some notes:
The key point is that the bits that encode integer type variables are identical to the binary sequence that you pass in as a string. Thus: bitwise operators. The only ones we need here are left bit-shift, which shifts each of the underlying bits one place to the left, and bitwise-or, which logically or's the bits of two numbers against one another. The equivalent representations render valid a pictorial understanding of the problem.
Rather than having to pass through the entire string to determine its length, and using that to inform the pow function, we can slot incoming bits in on the right.
Here's what's going on within the for loop:
1st pass:
sum <<= : 00000 /* more zero's contained in a long */
string: "10101"
ptr: ^
sum |= : 00001
2nd pass:
sum: 00010
string: "10101"
ptr: ^
sum: 00010
3rd pass:
sum: 00100
string: "10101"
ptr: ^
sum: 00101
... and so forth.
In general, rather than invoking
pow(2, arg)
you should leverage the bit-shift operator, which exactly accomplishes multiplication by some power of two. (Appending a zero is multiplication by 10 in base 10).

How to check whether a number is binary or 2's complement in C?

I was making a binary adder in C using only logic gates. Now for example, I wanted to add 4 + (-5) so I would get the answer in 2's complement and then convert it to decimal. In the same way, if I do, 4 + (-3) I would get the answer in binary and would like to use the same function to convert it to decimal.
Now, I know how to convert a 2's complement number into decimal, convert binary into decimal. But I want to use the same function to convert both 2's complement and binary into decimal. To do that, I have to figure out if the number is binary or 2's complement. It is where I am stuck.
Can someone give me an idea, algorithm or code in C to find out whether a number is 2's complement or normal binary?
SOURCE CODE
Chips
// Author: Ashish Ahuja
// Date created: 8-1-2016
// Descriptions: This file stores all the chips for
// the nand2tetris project.
// Links: www.nand2tetris.org
// class.coursera.org/nand2tetris1-001
// Files needed to compile successfully: ourhdr.h
int not (unsigned int a) {
if (a == 1) {
return 0;
}
else if (a == 0) {
return 1;
}
}
int and (unsigned int a, unsigned int b) {
if (a == 1 && b == 1)
return 1;
else if ((a == 1 && b == 0) || (a == 0 && b == 1) || (a == 0 && b == 0))
return 0;
}
int nand (unsigned int a, unsigned int b) {
unsigned int ans = 10;
ans = and (a, b);
unsigned int ack = not (ans);
return ack;
}
int or (unsigned int a, unsigned int b) {
return (nand (not (a), not (b)));
}
int nor (unsigned int a, unsigned int b) {
return (not (or (a, b)));
}
int xor (unsigned int a, unsigned int b) {
unsigned int a_r;
unsigned int b_r;
unsigned int sra;
unsigned int srb;
a_r = not (a);
b_r = not (b);
sra = nand (a_r, b);
srb = nand (b_r, a);
return nand (sra, srb);
}
int xnor (unsigned int a, unsigned int b) {
return (not (xor (a,b)));
}
Ourhdr.h
include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <math.h>
#include <time.h>
#include <stdbool.h>
#include <termios.h>
#include <stddef.h>
#include <sys/types.h>
#include <my/signal.h>
#include <my/socket.h>
#include <my/io.h>
#include <my/lib.h>
#include <my/tree.h>
#include <my/bits.h>
#include <my/binary.h>
//#include <my/error.h>
#define MAXLINE 4096
#define BUFF_SIZE 1024
Note: I am gonna only show headers needed by this project. So just think that the other headers are of no use.
Function to Convert array to integer
int array_num (int arr [], int n) {
char str [6] [2];
int i;
char number [13] = {'\n'};
for (i = 0; i < n; i ++)
sprintf (str [i], "%d", arr [i]);
for (i = 0; i < n; i ++)
strcat (number, str [i]);
i = atoi (number);
return i;
}
Function to get bits of an int, and return an pointer to an array containing bits
int *get_bits (int n, int bitswanted) {
int *bits = malloc (sizeof (int) * bitswanted);
int k;
int mask;
int masked_n;
int thebit;
for (k = 0; k < bitswanted; k ++) {
mask = 1 << k;
masked_n = n & mask;
thebit = masked_n >> k;
bits [k] = thebit;
}
return bits;
}
Function to convert binary to decimal, and vice-versa
int convert_num (int n, int what) {
int rem;
int i;
int binary = 0;
int decimal = 0;
switch (what) {
case 0: // Convert decimal to binary
i = 0;
rem = 0;
while (n != 0) {
rem = n % 2;
n /= 2;
binary += rem * i;
i *= 10;
}
return binary;
break;
case 1: // Convert binary to decimal
i = 0;
rem = 0;
while (n != 0) {
rem = n % 10;
n /= 10;
decimal += rem*pow (2, i);
i ++;
}
return decimal;
break;
}
}
Main program design
Read two numbers n1 and n2 from user
Get an pointer bits1 and bits2 which point to an array which have the bits of n1 and n2. Note, that the array will be in reverse order, i.e, the last bit will be in the 0th variable of the array.
Put a for loop in which you will pass three variables, i.e, the bits you want to add and carry from the last adding of bits operation.
The return value will be the the addition of the three bits and carry, will be changed to the carry after the addition (if any). Eg- You pass 1 and 0, and carry is 1, so, the return will be 0 and carry will be again changed to 1.
The return will be stored in another array called sum.
The array sum will be converted to an int using the function I have given above.
Now this is where I am stuck. I now want to change the int into a decimal number. But to do that, I must know whether, it is in form of a 2's compliment number, or just a normal binary. I do not know how to do that.
NOTE: The nand2tetris project is done in hdl but I was familiar to do it with C. Also, many of the function I have mentioned above have been taken from stackoverflow. Although, the design is my own.
Both are binary. The difference is signed or unsigned. For >0 this is the same. For <0 you can see that it is a negative number just by looking at the highest bit. Using the same function for output can easily be done by looking at the highest bit, if it is set output '-' and convert the negative two's complement to its abs() which can easily be done bitwise.
CAUTION: If a positive number is big enough to set the highest bit, it can no longer be distinguished from negative two's complement. That is the reason why programming languages do need separate types for this (e.g. in C int and unsigned).
Fun fact about 2s complement - and reason it has become so widely used is:
For addition you don't need to know if it is negative or positive. Just add as unsigned.
Subtraction is similar, but you have to negate the second operand (see below).
The only thing you might have to care about is overflow. For that you have to check if the sign of the result can actually result from the signs of the two inputs and a addition-overflow from the pre-most to the most signigficant bit.
Negation of int n is simply done by 0 - n. Alternatively, you can invert all bits and add 1 - that's what a CPU or hardware subtracter basically does.
Note that 2's complement binaries have an asymmetric range: -(N+1) ... N.
For conversion, just check for the minimum value (must be treated seperately) and output directly, otherwise get the sign (if ( n < 0 )) and negate the value (n = -n) and finally convert the -then unsigned/positive - value to a string or character stream.

Binary to decimal in c

I have a simple code to convert binary to decimal numbers. In my compiler, the decomposition works just fine for number less than 1000, beyond the output is always the same 1023. Anybody has an idea ?
#include <stdio.h>
#include <stdlib.h>
// how many power of ten is there in a number
// (I don't use the pow() function to avoid trouble with floating numbers)
int residu(int N)
{
int i=0;
while(N>=1){
N=N/10;
i++;
}
return i;
}
//exponentiating a number a by a number b
int power(int a, int b){
int i;
int res=1;
for (i=0;i<b;i++){res=a*res;}
return res;
}
//converting a number N
int main()
{
int i;
//the number to convert
int N;
scanf("%d",&N);
//the final decimal result
int res=0;
//we decompose N by descending powers of 10, and M is the rest
int M=0;
for(i=0;i<residu(N);i++){
// simple loop to look if there is a power of (residu(N)-1-i) in N,
// if yes we increment the binary decomposition by
// power(2,residu(N)-1-i)
if(M+ power(10,residu(N)-1-i) <= N)
{
M = M+power(10,residu(N)-1-i);
res=power(2,residu(N)-1-i)+res;
}
}
printf("%d\n",res);
}
Yes try this :
#include <stdio.h>
int main(void)
{
char bin; int dec = 0;
while (bin != '\n') {
scanf("%c",&bin);
if (bin == '1') dec = dec * 2 + 1;
else if (bin == '0') dec *= 2; }
printf("%d\n", dec);
return 0;
}
Most likely this is because you are using an int to store your binary number. An int will not store numbers above 2^31, which is 10 digits long, and 1023 is the largest number you can get with 10 binary digits.
It would be much easier for you to read your input number as a string, and then process each character of the string.
After a little experimentation, I think that your program is intended to accept a number consisting of 1's and 0's only as a base-10 number (the %d reads a decimal number). For example, given input 10, it outputs 2; given 1010, it outputs 10; given 10111001, it outputs 185.
So far, so good. Unfortunately, given 1234, it outputs 15, which is a little unexpected.
If you are running on a machine where int is a 32-bit signed value, then you can't enter a number with more than 10 digits, because you overflow the limit of a 32-bit int (which can handle ±2 billion, in round terms). The scanf() function doesn't handle overflows well.
You could help yourself by echoing your inputs; this is a standard debugging technique. Make sure the computer got the value you are expecting.
I'm not going to attempt to fix the code because I think you're going about the problem in completely the wrong way. (I'm not even sure whether it's best described as binary to decimal, or decimal to binary, or decimal to binary to decimal!) You would do better to read the input as a string of (up to 31) characters, then validate that each one is either a 0 or a 1. Assuming that's correct, then you can process the string very straight-forwardly to generate a value which can be formatted by printf() as a decimal.
Shift left is the same than multiply by 2 and is more efficient, so I think it is a more c-like answer:
#include <stdio.h>
#include <stdlib.h>
int bin2int(const char *bin)
{
int i, j;
j = sizeof(int)*8;
while ( (j--) && ((*bin=='0') || (*bin=='1')) ) {
i <<= 1;
if ( *bin=='1' ) i++;
bin++;
}
return i;
}
int main(void)
{
char* input = NULL;
size_t size = 0;
while ( getline(&input, &size, stdin) > 0 ) {
printf("%i\n", bin2int(input));
}
free(input);
}
#include <stdio.h> //printf
#include <string.h> //strlen
#include <stdint.h> //uintX_t or use int instead - depend on platform.
/* reverse string */
char *strrev(char *str){
int end = strlen(str)-1;
int start = 0;
while( start<end ){
str[start] ^= str[end];
str[end] ^= str[start];
str[start] ^= str[end];
++start;
--end;
}
return str;
}
/* transform binary string to integer */
uint32_t binstr2int(char *bs){
uint32_t ret = 0;
uint32_t val = 1;
while(*bs){
if (*bs++ == '1') ret = ret + val;
val = val*2;
}
return ret;
}
int main(void){
char binstr[] = "1010101001010101110100010011111"; //1428875423
printf("Binary: %s, Int: %d\n", binstr, binstr2int(strrev(binstr)));
return 0;
}

Resources