I am trying to create a program that will output the binary code for 16 numbers. Here is what i have so far:
#include <stdio.h>
#include <stdlib.h>
int i;
int count;
int mask;
int i = 0xF5A2;
int mask = 0x8000;
int main()
{
printf("Hex Value= %x Binary= \n", i);
{
for (count=0; count<15; count++1)
{
if (i&mask)
printf("1\n");
else
printf("0\n");
}
(mask = mask>>1);
}
return 0;
}
The error:
|16|error: expected ')' before numeric constant|
Also let me know if I have any other mistakes, Thanks in advance!
The error is referring to this expression:
count++1
Which makes no sense.
I assume you want:
count++
Making the line
for (count=0; count<15; count++)
You have other strangeness in your code such as:
int i; // Declare an integer named "i"
int mask; // Declare an integer named "mask"
int i = 0xF5A2; // Declare another integer also named "i". Did you forget about the first one???
int mask = 0x8000; // Did you forget you already declared an integer named "mask"?
printf("Hex Value= %x Binary= \n", i);
{
[...]
} // Why did you put a bracket-scope under a PRINTF call?
// Scopes typically follow loops and if-statements!
(mask = mask>>1); // Why put parens around a plain-old expression??
After fixing weirdness in your code, it should look like:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0xF5A2;
int mask = 0x8000;
printf("Hex Value= %x Binary= \n", i);
for (int count=0; count<15; ++count, mask>>=1)
{
printf("%d\n", (i&mask)? 1 : 0);
}
return 0;
}
Related
I have to make a program which prints all the bits of one byte union (which can't be any bigger than that), without using bitwise operators. I got a problem to build suitable union which has only one byte because to my knowledge I can't use struct now, because struct has 4 bytes. This is what I've done already:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "bit_set.h"
int main(void) {
printf("Input number: ");
if (scanf("%hhu", &word.x) == 0) {
printf("Incorrect input");
return 1;
}
printf("%u %u %u %u %u %u %u %u", word.a+0, word.a+1, word.a+2, word.a+3, word.a+4, word.a+5, word.a+6, word.a+7);
return 0;
}
#ifndef bit_set
#define bit_set
typedef unsigned char byte;
byte x;
union bit {
unsigned int i : 1;
}foo;
union bit_set
{
union bit a[8];
byte x;
}word;
#endif
Maybe the point of this task is to use arithmetic operations instead of the bitwise ones?
Here is an example:
void printByteBits(unsigned char num)
{
const static int div[8] = {1, 2, 4, 8, 16, 32, 64, 128};
for (int i = 0; i < sizeof(div)/sizeof(div[0]); i++)
{
printf("Bit %d: %d\n", i, (num / div[i]) % 2);
}
}
See the output here: https://godbolt.org/z/xUC663
To print a byte in binary wit the most significant bit first you can do something like this:
void print_bits (unsigned char x)
{
int i;
for (i = 0; i < 8; i++) {
if (x >= 0x80)
printf("1");
else
printf("0");
x = x / 2;
}
}
Though in general I would advise to use bitwise operators as they translate better to machine code resulting in better performance. The same function looks something like this:
void print_bits (unsigned char x)
{
int i;
for (i = 0; i < 8; i++) {
if (x & 0x80 != 0)
printf("1");
else
printf("0");
x = x << 1;
}
}
Note that your code prints the least significant bit first, which is not how binary is usually represented.
I am a beginner starting in C and am doing some exercises on codewars. The exercise requires me to take a decimal int, convert it into binary and output the number of 1s in the binary number. Below my incomplete code. I store the binary in int b and I want to output it into an array so that I can run a loop to search for the 1s and output the sum.
Thanks in advance!
#include <stddef.h>
#include <stdio.h>
//size_t countBits(unsigned value);
int countBits(int d);
int main() {
int numD = 1234;
int numB = countBits(numD);
printf("The number %d converted to binary is %d \n", numD, numB);
}
int countBits(int d) {
if (d < 2) {
return d;
} else {
int b = countBits(d / 2) * 10 + d % 2; //convert decimal into binary
int c;
int bArray[c];
}
Your function is almost correct:
you should define the argument type as unsigned to avoid problems with negative numbers
you should just return b in the else branch. Trying to use base 10 as an intermediary representation is useless and would fail for numbers larger than 1023.
Here is a corrected version:
int countBits(unsigned d) {
if (d < 2) {
return d;
} else {
return countBits(d / 2) + d % 2;
}
}
There are many more efficient ways to compute the number of bits in a word.
Check Sean Eron Anderson's Bit Twiddling Hacks for classic and advanced solutions.
You can make an array char as one of the replies said, for example:
#include <stdio.h>
#include <string.h>
int main(){
int count=0;
int n,bit;
char binary[50];
printf("Enter a binary: \n");
scanf("%s",binary);
n=strlen(binary);
for(int i=0;i<n;i++){
bit=binary[i]-'0';
if (bit==1){
count=count+1;
}
}
printf("Number of 1's: %d\n",count);
return 0;
}
This should count the number of 1's of a given binary.
Try something like this!
edit: I know that binary[i]-'0' might be confusing, if you don't understand that..take a look at this:
There are definitely 'smarter'/more compact ways to do this, but here is one way that will allow you to count bits of a bit larger numbers
#include <stdio.h>
int count_bits(int x)
{
char c_bin[33];
int count=0;
int mask=1;
for( int i =0; i < 32; i++){
if (x & mask ){
count=i+1;
c_bin[31-i]='1';
}
else{
c_bin[31-i]='0';
}
mask=mask*2;
}
c_bin[32]='\0';
printf("%d has %d bits\n",x,count);
printf("Binary x:%s\n",c_bin);
return count;
}
int main()
{
int c=count_bits(4);
return 0;
}
i am trying to create simple game. Task is to create program that calculate size of int in bites.
Their code is
#include <stdio.h>
int intSize(void)
{
unsigned int x,
i = 0;
x = ?;
while ((?) != 0)
?;
return ?;
}
int main()
{
printf("Size is %d bits\n",?);
return 0;
}
? is place where i should put my code.
This is what one of my tries
#include <stdio.h>
int intSize(void)
{
unsigned int x,
i = 0;
x = 0;
while ((x>>1) != 0)
i++;
return i;
}
int main()
{
printf("Size ise %d bits\n", intSize());
return 0;
}
I know that usigned int is 4bytes so i use bitwise operation to move bits it should be 32 but i am getting 1. I will be thankfull for any help.
Having
x = 0;
while ((x>>1) != 0)
...
the while stops immediately, so i is unchanged and the return value is 0.
The right way was to initialize x with~0u to have all bits valuing 1 (suppose 2-complements)
Out of that the test is not the right one and you missed to modify the value of x.
In
printf("Size ise %d bits\n", intSize);
you missed the () to call the function, currently you try to write its address, I say try because an address must be printf with the format %p.
Finally:
#include <stdio.h>
int intSize(void)
{
unsigned int x,
i = 0;
x = ~0u;
while ((x & 1) != 0)
(i+= 1, x /= 2); /* not x >= 1 in case it is a rotate rather than a shift */
return (int) i;
}
int main()
{
printf("Size is %d bits\n", intSize());
return 0;
}
Compilation and execution:
pi#raspberrypi:/tmp $ gcc -Wall s.c
pi#raspberrypi:/tmp $ ./a.out
Size is 32 bits
pi#raspberrypi:/tmp $
So in order the '?' are :
~0u
x & 1
(i+= 1, x /= 2)
(int) i
I'd solve this problem by putting a 1 in the low bit of an integer and shift left until it's zero, which means the bit clocked all the way out.
#include <stdio.h>
int intSize(void)
{
unsigned int x,
i = 0;
x = 1;
while ((x <<= 1) != 0)
i++;
return i+1;
}
int main()
{
printf("Size is %d bits\n", /*?*/ intSize());
return 0;
}
No concerns about signed/unsigned as far as I can tell.
EDIT to reflect the ? placeholder requirements of the project.
I need to write a program which would take a number of any length, would put its digits in opposite order (for example from 12365 would make 56321) and check if those two numbers can be divided from all its digits. If both numbers can be divided from every digit then program should output both numbers: the given one and the opposite one. For now My program can only reverse that number.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int i, m, n, atb = 0, nr = 1, skait = 0, j;
printf("Iveskite intervalo pradzia ir pabaiga:\n");
scanf("%d", &m);
scanf("%d", &n);
//---
for(i = m; i <= n; i++)
{
int temp = i;
int dalys[skait];
do
{
atb = atb*10 + temp%10;
dalys[skait] = temp;
temp = temp / 10;
skait++;
}
while (temp != 0);
//-------------------------------------------
for(j = 1; j <= skait; j++){
int dal = pow(10,(skait-1));
}
//-------------------------------------------
printf("\n%d skaicius: %d", nr, atb);
printf("\nSkaicius susideda is %d skaitmenu.", skait);
atb=0;
skait=0;
nr++;
}
return 0;
}
I already started to try to solve the division part... but I cant find how to make the program take every digit and make it check that division part...
I've written also this version! I think is better of the previous! This solution uses a vector smaller than the version in the other reply and it doesn't make useless divisions! :) Furthermore the function compute() returns 1 if the condition requested are verified (0 elsewhere), then you may easily move the final printf out of the function in the main!
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#define SEESTEPS
#ifdef SEESTEPS
#define Dprintf(a...) printf(a);
#else
#define Dprintf(a...) ;
#endif
int compute(uint64_t x,int zeroGo)
{
uint64_t y,z,t;
int div[10];
int cntdiv,i;
for(i=0;i<10;i++)
div[i]=0;
z=x;y=0;cntdiv=0;
while(z) {
t=(z%10);
if (!div[t]) {
cntdiv++;
div[t]=1;
}
y*=10;y+=t;
z/=10;
}
Dprintf("%lu => Inverted %lu\n",x,y);
if (zeroGo || !div[0]) {
t=div[0];
for(i=1;i<10;i++) {
if (!div[i])
continue;
Dprintf("%lu mod %d = %lu\n",x,i,x%i );
if ( (x%i) )
break;
Dprintf("%lu mod %d = %lu\n",y,i,y%i );
if ( (y%i) )
break;
t++;
}
} else {
t=cntdiv-1;
}
//Dprintf("%d %d -",cntdiv,t);
if ((int)t==cntdiv) {
printf("%lu %lu\n",x,y);
return 1;
}
return 0;
}
int main(void) {
uint64_t f,t;
int cnt=0;
printf("From...: ");
scanf("%lu",&f);
printf("To.....: ");
scanf("%lu",&t);
for(;f<=t;f++)
cnt+=compute(f,1);
printf("%d\n",cnt);
return 0;
}
Try this! It should be run as you require! If you comment the code #define SEESTEPS the code prints only the required result! This code computes only one number at time, you may transform it in a function!!!
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define SEESTEPS
#ifdef SEESTEPS
#define Dprintf(a...) printf(a);
#else
#define Dprintf(a...) ;
#endif
int main(void) {
uint64_t x,y,z;
uint64_t div[20];
int cntdiv,i;
scanf("%lu",&x);
/* This inverts the number and computes the digit */
z=x;y=0;cntdiv=0;
while(z) {
div[cntdiv]=(z%10);
y*=10;y+=div[cntdiv];
z/=10;cntdiv++;
}
Dprintf("Inverted %lu\n",y);
/* This verifies the divisibility! */
for(i=0;i<cntdiv;i++) {
if (!div[i])
continue; /* Or break; if you prefer */
Dprintf("%lu mod %lu = %lu\n",x,div[i],x%div[i] );
if ( (x%div[i]))
break;
Dprintf("%lu mod %lu = %lu\n",y,div[i],y%div[i] );
if ( (y%div[i]))
break;
}
if (i==cntdiv)
printf("%lu %lu",x,y);
return 0;
}
I am passing in an array into a function straightflush. I use a counting loop so i can get to all of the elements but for some reason, even tho the counter i increases, i get the value and suit for the first element of the array. Therefore, only my spadesCount increases as it always shows 4 for the value and spade for the suit.
struct card{
int value;
char suit;
};
int straightflush(struct card hand[], int n)
{
int clubsCount = 0;
int diamondsCount = 0;
int heartCount = 0;
int spadesCount =0;
int i;
for(i=0; i<n; i++)
{
if (hand[i].suit == 'c')
{
clubsCount++;
}
else if (hand[i].suit == 'd')
{
diamondsCount++;
}
else if (hand[i].suit == 'h')
{
heartCount++;
}
else{
spadesCount++;
}
}
return 0;
}
here is my main:
int main(){
struct card hand1[] = {{4,'s'}, {9,'s'},{12,'c'},{11,'s'},{8,'s'},
{6,'d'}, {3,'d'},{7,'s'},{10,'s'},{12,'d'}};
printf ("%d\n", straightflush(hand1, 10));
}
I just run your code and the four count variables have correct values. I think it's because you are returning 0 at the end of your straightflush function, the output is always 0.
You can use a debugger or add the following line before the return statement in straightflush() to prove that your counts are actually accurate.
printf("%d %d %d %d\n", clubsCount, diamondsCount, heartCount, spadesCount);
Your return value has nothing to do with the values you read thus the printf statement in your main() function is not printing the count of any thing, it is just printing 0 no matter what.
If you want the counts accessible outside of striaghtflush() you need to either use global variables for those counts (a generally shunned idea) or pass some values in by reference. An example of this would be:
#include <stdio.h>
#include <stdlib.h>
void editValues( int *numDiamonds, int *numClubs, int *numHearts, int *numSpades ){
*numDiamonds = 3;
*numClubs = 5;
*numHearts = 7;
*numSpades = 11;
}
int main(int argc,char**argv)
{
int numD=0, numC=1, numH=2, numS=3;
printf("%d %d %d %d\n", numD, numC, numH, numS);
editValues(&numD, &numC, &numH, &numS);
printf("%d %d %d %d\n", numD, numC, numH, numS);
return 0;
}