I'm making a program in C. I am to extract bytes. un8 extractbyte (int r, int pos) should return byte number pos from number r. As example, I use as input: 0x7788AABB. Output then should be:
Part number 0 is BB
Part number 1 is AA
Part number 2 is 88
Part number 3 is 77
I am stuck at the last part of the program, where I have put the question marks in the comments. Those lines aren't right and I am confused in how I should make it work... The output I get now is bb at every part. I am pretty new at C by the way.
#include <stdio.h>
#include <stdlib.h>
typedef unsigned int un32;
typedef unsigned char un8;
un8 extractbyte (un32 r, un8 pos);
int main ()
{
un32 number;
un8 k;
printf("Enter a number:\n");
scanf("%x",&number);
for (k=0; k<=3;k++)
printf ("Part number %d is: %x \n", k , extractbyte(number, k) );
return 0;
}
un8 extractbyte (un32 r , un8 pos)
{
un32 mask;
un32 size = pos*8;
un32; // ??
un8; // ??
return (un8) r; // ??
}
un8 extractbyte(un32 r, un8 pos)
{
return (r >> (8 * pos)) & 0xFF;
}
I would make your extractbyte function something like this.
int extractbyte(int n, int pos)
{
return (n >> (pos * 8)) & 0xff;
}
#include <stdio.h>
char extractbyte(int number, int v) {
char *x=(char *)&number;
return x[3-v];
}
int main() {
int n=0x7788aabb;
int i;
for (i=0; i<4; i++) {
printf("%d) %x\n",i,(unsigned char)extractbyte(n,i));
}
return 0;
}
Related
I am having a bit of difficulty understanding the arguments for fscanf. The first two are self-explanatory. The first argument is the point file. It gets the content from this file. The second argument is the type of content in the file. In this case it's int so there is usage of %d. Now, the third argument, I am having difficulty discerning and it would help to have it done in some other way, so I can better understand what this 3rd argument is all about.
#include <stdio.h>
#include <string.h>
int main(void);
void getCode(char a[]);
int getMessage(int a[]);
void sortMessage(int a[], int b);
void decodeMessage(char a[], int b[], int c);
int main(void) {
// declare file names
char string[53];
int integers[27];
int msgSize;
// int codeSize = 52;
// Open files & there content
getCode(string);
msgSize = getMessage(integers);
sortMessage(integers, msgSize);
decodeMessage(string, integers, msgSize);
}
void getCode(char string[]) {
// get content from code file & print it
FILE *C = fopen("codefile.txt", "r");
while (fgets(string, 55, C)) {
printf("%s\n", string);
}
}
getMessage(int integers[]) {
// Get content from message file & return it
FILE *M;
M = fopen("msgfile.txt", "r");
int counter = 0;
/* Read one number at a time from the file and store it */
while (!feof(M)) {
fscanf(M, "%d", (integers + counter));
counter++;
}
/* Close the file */
// fclose(M);
return (counter);
}
The third, and subsequent parameters if used, are pointers to the destinations of the parsed values. The better way to write that is &arrayname[index] because it more clearly indicates you are using a type size array index as a pointer. Note that newlines are just like any other whitespace.
Try this yourself
Single Example :
#include <stdio.h>
void main()
{
int count=3;
int ints[3];
printf("Give me %d:\n",count);
for (int i=0;i<count;i++)
scanf("%d",&ints[i]);
printf("You said:\n");
for (int i=0;i<count;i++)
printf("%d\n",ints[i]);
}
Result:
Give me 3:
12
23
34
You said:
12
23
34
Multiple Example: (which could allow you to mix types, or fork into more arrays).
#include <stdio.h>
void main ()
{
int count = 6;
int ints[6];
printf ("Give me %d :\n", count);
for (int i = 0; i < count; )
{
int got;
got= scanf ("%d %d %d", &ints[i], &ints[i + 1], &ints[i + 2]);
i+= got;
}
printf ("You said:\n");
for (int i = 0; i < count; i ++)
printf ("%d\n", ints[i]);
}
Result:
Give me 6 :
1 2 3
4
5 6
You said:
1
2
3
4
5
6
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 a segment tree for a competitive coding problem and this tree is represented using an array. I have functions namely, rangeMinQuery and updateTree which perform intermediate jobs on the array. I am unable to figure out how to manipulate the said array using the functions.
#include <stdio.h>
#include <stdlib.h>
#define bool int
#define MAX(a,b) (((a)>(b))?(a):(b))
int upper_power_of_two(int v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
int getMid(int s, int e)
{
return s + (e -s)/2;
}
void updateValueUtil(int segTree[], int ss, int se, int i, int diff, int si)
{
// Base Case: If the input index lies outside the range of
// this segment
if (i < ss || i > se)
return;
// If the input index is in range of this node, then update
// the value of the node and its children
st[si] = st[si] + diff;
if (se != ss)
{
int mid = getMid(ss, se);
updateValueUtil(st, ss, mid, i, diff, 2*si + 1);
updateValueUtil(st, mid+1, se, i, diff, 2*si + 2);
}
}
void updateValue(int arr[], int segTree[], int n, int i, int new_val)
{
// Get the difference between new value and old value
int diff = new_val - arr[i];
// Update the value in array
arr[i] = new_val;
// Update the values of nodes in segment tree
updateValueUtil(st, 0, n-1, i, diff, 0);
}
int rangeMinquery(int segTree[],int qlow,int qhigh,int low,int high,int pos)
{
if(qlow<=low && qhigh >=high)
return segTree[pos];
if(qlow>high || qhigh <low)
return 9999999999;
int mid=(low+high)/2;
return MAX(rangeMinquery(segTree,qlow,qhigh,low,mid,2*pos+1),rangeMinquery(segTree,qlow,qhigh,mid+1,high,2*pos+2));
}
int main()
{
int n,q,x,l,r,i;
scanf("%d %d %d %d",&n,&q,&l,&r);
int a[n];
int segTree[upper_power_of_two(n)];
printf("%d\n",upper_power_of_two(n));
while(q--)
{
int cmd,pos1,pos2;
scanf("%d %d %d",&cmd,&pos1,&pos2);
if(cmd==1)
{
a[pos1]+=pos2;
updateValue(a,segTree,n,1,0);
}
if(cmd==2)
{
x=rangeMinquery(segTree,pos1,pos2,0,n,0);
printf("%d\n",x);
}
}
return 0;
}
As you can see, I am trying to manipulate the array segTree and retain the values there itself. I would also like to know if there's a method to achieve the same on JAVA perhaps?
You can make global pointer...
//in global scope
int *segTree;
... and create array using malloc() operator:
//in main()
segTree = malloc(upper_power_of_two(n) * sizeof(int));
And now your array is global. But remember to free(segTree) before you end your program.
Btw. You should never create local arrays (on stack) with variable size like you did in given code.
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();
}
}