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.
Related
I encountered a hard question I don't know the answer to: "Rearrange the digits from an integer in blocks of two with a recursive function" here's an example:
Input: 123456
unsigned long pairinvPrint(unsigned long number) {
printf("%d", number % 100);
if ((number / 100) <= 99) {
printf("%d", number / 100);
}
else {
pairinv(number / 100);
}
}
Output: 563412
More I/O Examples: 42 -> 42; 1234 -> 3412
However, the set circumstances to do this are hard (no loops, arrays, pointers, global- or static variables, no libraries) and it should not print the solution directly, rather return it upon a call like this:
printf("Rearrange int (%lu) = %lu", input, pairinvert(input));
Luckily there's one circumstance to make it easier, the number of the input digits is always even.
Now I experimented for a while, but cant come up with a working solution, except the invalid one using printf.
Does anyone have some inspiration for me or idea how to tackle this?
I'll bite :-)
unsigned long p(unsigned long p1, unsigned long p2) {
// no loops, no arrays, no pointers, no global, no static, no variables, no libraries
if (p1 < 100) return p2*100 + p1;
return p(p1/100, p2*100 + p1%100);
}
unsigned long pairinvert(unsigned long n) {
// no loops, no arrays, no pointers, no global, no static, no variables, no libraries
if (n < 100) return n;
return p(n/100, n%100);
}
// need <stdio.h> for printf()
#include <stdio.h>
int main(void) {
unsigned long input;
input = 123456;
printf("Rearrange int (%lu) = %lu\n", input, pairinvert(input));
input = 42;
printf("Rearrange int (%lu) = %lu\n", input, pairinvert(input));
input = 1234;
printf("Rearrange int (%lu) = %lu\n", input, pairinvert(input));
}
Following program should work.
#include <stdio.h>
void rearrange(int n, int *output) {
int lsd = 0, slsd = 0;
if(n == 0)
return;
if(n > 0) {
lsd = n%10;
}
if (n > 9) {
slsd = (n%100)/10;
}
*output = 100*(*output) + 10*slsd + lsd;
n = n/100;
rearrange(n, output);
}
int main() {
int n;
int output = 0;
scanf("%d", &n);
rearrange(n, &output);
printf("%d\n", output);
return 0;
}
It is simple to understand, so I am not writing any comments.
Note that it is tail recursive so with O2 optimization it can recurse infinitely.
Try this :
unsigned long pairinv(unsigned long number, unsigned long result) {
unsigned long n = number % 100; // Gets the two digit number
if (n == 0) return result; // If it's zero returns the result
result = result * 100 + n; // Else multiplies the result by 100, adds n
return pairinv(number / 100, result); // and continues by recursion
}
int main() {
unsigned long r= 0;
printf("%lu\n", pairinv(123456, r)); //==> 563412
return 0;
}
Doing the 7. Reverse Integer leetcode, (intput =321 expected output = 123)
I don't know how to return my numbers from the function. I'm printing them as of right now to see if I'm solving the problem, and my stdout is fine but my output is 3.
Your input:
123
stdout:
312
Output:
3
Expected:
321
int reverse(int x)
{
int a,b,c;
c = x % 10;
b = (x / 10) / 10;
a = (x / 10) % 10 ;
printf("%d%d%d",c,b,a);
return;
}
It might be easier to generalize reverse to handle numbers of any width, not just 3 digits.
Here's some code to do that (you might have to adjust the format for the printf):
#include <stdio.h>
int
reverse(int x)
{
int y = 0;
while (x != 0) {
y *= 10;
y += (x % 10);
x /= 10;
}
return y;
}
int
main(void)
{
const char *fmt = " %3.3d";
for (int x = 0; x <= 999; ++x) {
printf(fmt,x);
printf(fmt,reverse(x));
printf("\n");
}
return 0;
}
Generalizing a bit and handling potential negative values. You have the basic approach, but, in addition, you want to determine the sign of the input and then operate on a positive value and restore the sign at the end of your function. You can do something similar to:
#include <stdio.h>
#include <stdlib.h>
int reverseint (int n)
{
int reverse = 0,
sign = n < 0 ? -1 : 1;
if (n < 0)
n = -n;
while (n) {
reverse *= 10;
reverse = reverse + n % 10;
n /= 10;
}
return sign * reverse;
}
A short example main() to demonstrate that takes the number to reverse as the first argument to the program (or uses 54321 if no argument is given) could be:
int main (int argc, char **argv) {
int n = (argc > 1) ? (int)strtol(argv[1], NULL, 0) : 54321;
printf ("n : %d\nreverse : %d\n", n, reverseint(n));
}
(note: you should validate the input to the program and the reverseint function are valid integers is in the range of int -- that is left to you)
Example Use/Output
$ ./bin/reverseint
n : 54321
reverse : 12345
$ ./bin/reverseint 0
n : 0
reverse : 0
$ ./bin/reverseint -12345
n : -12345
reverse : -54321
Alternative Using div()
The div() function also provides a nice variant that will replace both your division and modulo operations. See man 3 div. The following is equivalent to the function above but using div() instead of / and %:
int reverseint (int n)
{
/* initialize div_t with positive .quot */
div_t d = { .quot = n < 0 ? -n : n };
int reverse = 0,
sign = n < 0 ? -1 : 1;
do {
d = div (d.quot, 10); /* call div with base 10, to update quotient */
reverse *= 10; /* multiply reverse by 10 */
reverse += d.rem; /* add remainder of division */
} while (d.quot);
return sign * reverse;
}
Look things over and let me know if you have further questions.
As already said you mixed up a and b.
You can't return multiple values.
What you can do is create one number, pack the numbers in an array, pass the pointers to function, place in a struct. You could write something like this:
#include <stdio.h>
int reverse(int x)
{
int a,b,c;
int num;
c = x % 10;
b = (x / 10) % 10;
a = (x / 10) / 10 ;
num = c*100 + b*10 + a;
return num;
}
int main()
{
int x;
scanf("%d", &x);
int num = reverse(x);
printf("%d", num);
}
If you want to return all the values separately you can write something like this for example:
#include <stdio.h>
void reverse(int x , int *a, int *b, int *c)
{
*c = x % 10;
*b = (x / 10) % 10;
*a = (x / 10) / 10 ;
}
int main()
{
int x,a,b,c;
scanf("%d", &x);
reverse(x,&a,&b,&c);
printf("%d%d%d",c,b,a);
}
since you don't want to "return" a single number without the addition operation and display the reversed digits as a whole number there is a way of solving this via the usage of pointers. The code goes like this;
#include <stdio.h>
int* reverse(int);
int main() {
int inputnum;
int *p;
printf("Enter input number: ");
scanf("%d", &inputnum);
p=reverse(inputnum);
printf("\n Output number: ");
for(int i=0;i<3;i++){
printf("%d", *p );
p++;
}
return 0;
}
int* reverse(int x)
{
static int arr [3];
arr[0] = x % 10;
arr[1] = (x / 10) / 10;
arr[2] = (x / 10) % 10 ;
return arr;
}
As you can see, you don't need to use additional integer variables such as a,b,c since we will be storing the data of each operation you have done in a array and treat it as your new number as a whole in the output part. We do this since this is what you specifically asked in your question but there are so much more simpler ways on digit reversing etc. After returning the array that represents the new output number, we can ask our pointer to start from the first index of the array (which is the last digit of the input number in this case) untill the end. By increasing the pointer by 1 we display other digits of our input number as reversed. I hope this will be helpful
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 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;
}
Jus check out this program.Logically it seems fine but its giving 000000000000000000000 for everything
#include<stdio.h>
void main()
{
int n=25,k=32;
printf("binary equivalent\n");
while(k!=0)
{
if((n>>1&0x01)!=0)
printf("1");
else
printf("0");
k--;
}
}
You don't ever change n.
Don't try and cram everything into one line, be a little more verbose so that things are clearer.
while(k!=0)
{
if((n & 0x01) != 0)
printf("1");
else
printf("0");
k--;
n >>= 1;
}
That is because you don't change n.
For n=25 we have (n>>1)=12 hence it prints zero. And since you don't change n it prints zero for all k.
You can change it in the following way:
#include
void main()
{
int n=25,k=32;
printf("binary equivalent\n");
while(k!=0)
{
if((n & 0x01)!=0)
printf("1");
else
printf("0");
k--;
n = n >> 1;
}
}
However it will print binary presentation in reversed form.
Your n is never getting changed:
if((n>>1&0x01)!=0)
should be
if(n & 0x01)
and add
n>>=1; after k--;
Also this will produce the binary representation in reverse order.
You are not modifying n - every time you compare 0x01 with second bit on n.
You don't change the value of n within the loop. And probably you want to test the least significant bit before shifting.
/*
* Author: Andrey Vlassov
* Date: Thu Apr 19 03:10:49 UTC 2012
*
* Description:
* An expample program demonstrating how
* to convert decimal integer number to
* binary representation
*
* NOTE:
* For simplicity additional check left out
*
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char help[] = ">>> Please provide an integer number as argument!!!";
char id[] = "d2b (c) Andrey Vlassov Apr 18, 2012 8:15PM PST";
if( argc < 2 ) {
printf("%s\n", help);
exit(0);
}
printf("\n%s\n\n", id);
int n = atoi(argv[1]);
int i, bites, bits, mask;
printf("Number is %d\n", n);
printf("size: %d bites\n", bites=sizeof(n));
printf("dec: %d\n", n);
printf("hex: %#x\n", n);
printf("oct: %#o\n", n);
printf("bin: b");
bits = bites*8-1;
mask = 0x01 << (bits-1);
for( i=0; i<bits; i++) {
printf("%d", ( n & mask ? 1 : 0 ) );
mask >>= 1;
}
printf("\n\n");
exit(0);
}
i think it will help the result is the same as other poster posted
#include<stdio.h>
int main()
{
int n=25;
int k=32;
printf("binary equivalent\n");
for (int i=0;i<32;i++){
if((n&1)!=0)
printf("1");
else
printf("0");
n>>=1;
}
}
as #falagar said result will be printed in reverse order
// how to print binary number representation of an integer
// using bitwise operators
//
// oon
// 18.04.2013
// Refs
// http://www.cs.northwestern.edu/~wms128/bits.c
// http://www.cs.cmu.edu/~guna/15-123S11/
#include <stdio.h>
#define no_of_bits_in_a_byte 8
#define get_bit(w,i) ((w>>i)&1)
void print_binary(signed int x);
int main()
{
print_binary(2); // 00000000000000000000000000000010
print_binary(-2); // 11111111111111111111111111111110
return 0;
}
void print_binary(signed int x)
{
int i;
int no_of_bytes = sizeof(x);
for (i=no_of_bytes*no_of_bits_in_a_byte-1; i>=0; i--) {
printf("%d",get_bit(x,i));
}
printf("\n");
}
/*
* print_binary2.c
*
* oon
*
* 19.04.2013
*/
// http://www.cs.northwestern.edu/~wms128/bits.c
// http://www.cs.cmu.edu/~guna/15-123S11/
#include <stdio.h>
#define no_of_bits_in_a_byte 8
#define get_bit(w,i) ((w>>i)&1)
void print_binary2(signed int x, unsigned int n);
int check_bits_fit_in_2s_complement(signed int x, unsigned int n);
void main()
{
print_binary2(2,2); // output: The signed integer 2 cannot be represented by 2 bit(s) in two complements form.
print_binary2(2,3); // output: 010
print_binary2(-2,2); // output: 10
print_binary2(-2,3); // output: 110
}
int check_bits_fit_in_2s_complement(signed int x, unsigned int n) {
int mask = x >> 31;
return !(((~x & mask) + (x & ~mask))>> (n + ~0));
}
void print_binary2(signed int x, unsigned int n)
{
// check if x can be represented by n bits in two's complement form.
if (check_bits_fit_in_2s_complement(x,n)) {
int i;
for (i=n-1; i>=0; i--) {
printf("%d",get_bit(x,i));
}
printf("\n");
} else {
printf("The signed integer %d cannot be represented by %u bit(s) in two complements form.\n",x,n);
}
}
The above code shows how to print binary number in two's complement form where n denotes the number of bits.
int binary(int n)
{
if(n/2)
binary(n/2);
printf("%d",n%2);
}
void main()
{
int n;
printf("enter any number");
scanf("%d",&n);
binary(n):
getch();
}
Try this!
#include<iostream>
#include<stack>
using namespace std;
int main(){
stack<int> st;
int n=25, k=32;
while(k!=0){
if((n&0x01)!=0)
st.push(1);
else
st.push(0);
k--;
n=n>>1;
}
while(!st.empty()){
cout<<st.top();
st.pop();
}
}