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.
Related
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.
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.
After reading the question how to get bit by bit data from a integer value in c?, I see that if I want to look at each bit in an integer, I should right shift the integer and mask it. But I wonder is it possible to access each bit in the memory without such a complicated code? By using pointer or something like that.
In C, bit wise operations, like shifting is one of the only ways to manipulate variables on the bit level. Its expressions can be somewhat "ugly" at first glance but like everything through practice, will soon be easy to understand.
Just keep at it.
Here's a great article for your interest:
A bit of fun: fun with bits
It is possible to do it without shifting and masking, but it's hardly less "complicated" to do so:
#include <stdio.h>
#include <stdbool.h>
unsigned int ui_pow(unsigned int base, unsigned int exponent)
{
unsigned int result = 1;
for ( unsigned int i = 1; i <= exponent; ++i ) {
result *= base;
}
return result;
}
bool bit_is_set_one(unsigned int n, unsigned int bit)
{
return (n >> bit) & 1;
}
bool bit_is_set_two(unsigned int n, unsigned int bit)
{
return (n / ui_pow(2, bit)) % 2;
}
int main(void)
{
bool all_equal = true;
for ( unsigned int i = 0; i < 65535; ++i ) {
for ( unsigned int j = 0; j < 16; ++j ) {
if ( bit_is_set_one(i, j) != bit_is_set_two(i, j) ) {
all_equal = false;
}
}
}
printf("Methods%s give equal results.\n", all_equal ? "" : " do not");
return 0;
}
which outputs:
paul#thoth:~/src/sandbox$ ./altshift
Methods give equal results.
paul#thoth:~/src/sandbox$
If you know the bit location, you can do a bit mask without doing the shift.
For example: (i & 0x02)
You'll get 0x02 if the 2nd bit from right is a 1, or 0x00 if the 2nd bit is a 0.
Usually a macro is used: #define BitMask(i) (1 << (i))
For a constant i, the shift will be handle in compilation stage, and it wont show up in final binaries.
This question already has answers here:
Conversion of Char to Binary in C
(3 answers)
Closed 9 years ago.
I want a really basic way to print out the binary representation of a char. I can't seem to find any example code anywhere.
I assumed you could do it in a few lines but everything I find is overly long and complex using lots of functions I haven't used before. atoi comes up a lot but it's not standard.
Is there a simple function or simple way of writing a function to take a char variable and then print out a binary representation?
Eg: char 'x' is the argument taken in by the function and "x is 0111 1000" is printed out.
It's for a school assignment where I must take user input of a string and print out the string in binary. I just need to get the basics of converting a char to binary but i'm struggling at the moment.
What you'd want to do is use bitwise operators to mask the bits one by one and print them to the standard output.
A char in C is guaranteed to be 1 byte, so loop to 8.
Within each iteration, mask off the highest order bit.
Once you have it, just print it to standard output.
Here is a quick stab which hopefully makes sense...
main() {
char a = 10;
int i;
for (i = 0; i < 8; i++) {
printf("%d", !!((a << i) & 0x80));
}
printf("\n");
return 0;
}
CodePad.
In order to get the bit, I shift to the left to get the numbered bit (highest to lowest so printing it is easy) and then mask it off. I then translate it to 0 or 1 with !!.
you can use this method
const char *byte_to_binary(int x)
{
static char b[9];
b[0] = '\0';
int z;
for (z = 128; z > 0; z >>= 1)
{
strcat(b, ((x & z) == z) ? "1" : "0");
}
return b;
}
to get the binary representation and print with it
for example
printf("%s\n", byte_to_binary(15));
void printBits(size_t const size, void const * const ptr)
{
unsigned char *b = (unsigned char*) ptr;
unsigned char byte;
int i, j;
for (i=size-1;i>=0;i--)
{
for (j=7;j>=0;j--)
{
byte = b[i] & (1<<j);
byte >>= j;
printf("%u", byte);
}
}
puts("");
}
int main(int argv, char* argc[])
{
int i = 23;
uint ui = UINT_MAX;
float f = 23.45f;
printBits(sizeof(i), &i);
printBits(sizeof(ui), &ui);
printBits(sizeof(f), &f);
return 0;
}
Try this:-
#include <limits.h>
char *chartobin ( unsigned char c )
{
static char bin[CHAR_BIT + 1] = {0};
int i;
for( i = CHAR_BIT - 1; i >= 0; i-- )
{
bin[i] = (c % 2) + '0';
c /= 2;
}
return bin;
}
How do you count the number of bits set in a floating point number using C functions?
#include <stdio.h> /* for printf() */
#include <limits.h> /* for CHAR_BIT */
int main(void) {
/* union method */
{
/* a union can only be initialized for the first option in the union */
union { float f; char cs[sizeof(float)]; } const focs = { 1.0 };
int j,k;
int count = 0;
for (j = 0; j < sizeof(float); j++)
{
char const byte = focs.cs[j];
for (k = 0; k < CHAR_BIT; k++)
{
if ((1 << k) & byte)
{
count++;
}
}
}
printf("count(%2.1f) = %d\n", focs.f, count);
}
/* cast method */
{
float const f = 2.5;
int j,k;
int count = 0;
for (j = 0; j < sizeof(float); j++)
{
char const byte = ((char *)&f)[j];
for (k = 0; k < CHAR_BIT; k++)
{
if ((1 << k) & byte)
{
count++;
}
}
}
printf("count(%2.1f) = %d\n", f, count);
}
return 0;
}
If you want to work on the actual bitwise representation of a floating point number, you should do something like this:
float f; /* whatever your float is */
int i = *(int *)&f;
What this does is take the address of f with the address-of operator, &. This address is of type float *, a pointer to a float. Then it recasts it with (int *), which says "pretend this pointer doesn't point to a float anymore, but now it points to an int". Note that it doesn't change the value at f at all. Then the last * (or first, since we read right-to-left) dereferences this pointer, which is a pointer to an int, and therefore returns an int, a.k.a. the integer with the same bitwise representation as the float.
To do the opposite (convert and int i back to a float f), do the opposite:
f = *(float *)&i;
Unless I am mistaken, this operation is undefined by the C standard, but will probably work on most computers and compilers. It is undefined because I believe the actual floating-point representation of numbers is implementation-dependent, and can be left to the CPU or the compiler, and therefore the value of i is almost impossible to predict after this operation (same goes for the value of f in the reverse operation). It is famously used in John Carmack's inverse square root function for the same nefarious purpose.
Anyway, if you're doing this in real code, you should probably stop and think twice about what you're trying to do and why you're using floats to do it. However, if you're just doing this out of curiosity, or you have thought about these and are sure of your design and methods, go for it.
I'm led to believe that you already know how to count the number of bits set in a regular integer, as this is a much easier task. If you don't know, your compiler (or the C language, I don't even know) may have a function to count bits, or you could use something from the wonderful Bit-Twiddling Hacks website, which has ways to do things like this with bitwise operations (which should be pretty fast).
A nice function for counting set bits in an integer mentioned by the first answer:
int NumberOfSetBits(int i)
{
i = i - ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
return ((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
}
To use it on your float you would do something like this:
//...
float f;
//...
int numBitsOfF = NumberOfSetBits(*(int*) &f);
You mean the bits set in the IEEE-754 single precision representation of a number? If so, cast it to int (both float and int are 32bit wide) and do a regular bit count: SO question #109023.
The following function will find the number of bits in a 32-bit number. Just type case your float with integer and call this function by a cast
float f=3.14f;
count_bits(*(int *)&f);
int count_bits(int v)
{
// count the number of bits set in v
int c; // c accumulates the total bits set in v
int b=v;
for (c = 0; v; c++)
{
v &= v - 1; // clear the least significant bit set
}
//printf("No of bits in %d is %d\n",b,c);
return c;
}