How do I set the bits of a variable to assume the pattern I want? For exemple, if I have to print this sequence, how do i proceed?
11010010 11010010 11010010 11010010
I wrote the code that print and separate bits in this configuration, but don't know how to set them as I want.
#include <stdio.h>
#include <limits.h>
int a;
void stampabit(a);
int main()
{
int i;
int n= sizeof(int) * CHAR_BIT;
int mask = 1 << (n-1);
for (i=1; i<=n; ++i){
putchar(((a & mask)==0)?'0':'1');
a<<=1;
if(i%CHAR_BIT==0 && i<n)
putchar(' ');
}
}
You must shift mask instead of shift the variable
#include <stdio.h>
#include <limits.h>
unsigned int a = 0xAA55AA55;
int main()
{
size_t i;
unsigned int n= sizeof(int) * CHAR_BIT;
unsigned int mask = 1 << (n-1);
for (i=1; i<=n; ++i){
putchar(((a & mask)==0)?'0':'1');
mask>>=1;
if(i%CHAR_BIT==0 && i<n)
putchar(' ');
}
putchar('\n');
}
Output will be
10101010 01010101 10101010 01010101
Changing value of a to 0xD2D2D2D2 as you want output will be
11010010 11010010 11010010 11010010
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With