Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern with bitwise operators

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(' ');
    }
}
like image 243
ennedes Avatar asked Jan 17 '26 13:01

ennedes


1 Answers

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 
like image 138
LPs Avatar answered Jan 20 '26 01:01

LPs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!