C/Data Type/Bit Shift
Содержание
A bit shift example
#include <stdio.h>
int main(void)
{
unsigned int i;
int j;
i = 1;
/* left shift i by 1, which is same as a multiply by 2 */
for(j = 0; j < 6; j++) {
i = i << 1;
printf("Left shift %d: %d\n", j, i);
}
/* right shift i by 1, which is same as a division by 2 */
for(j = 0; j < 4; j++) {
i = i >> 1;
printf("Right shift %d: %d\n", j, i);
}
return 0;
}
Shift bitwise and display the result
#include <stdio.h>
void show_binary(unsigned u);
int main(void)
{
unsigned short u;
u = 45678;
show_binary(u);
u = u << 1;
show_binary(u);
u = u >> 1;
show_binary(u);
return 0;
}
void show_binary(unsigned u)
{
int n;
for( n = 32768; n > 0; n = n / 2 )
if(u & n)
printf("1 ");
else
printf("0 ");
printf("\n");
}
Shift statement in for
#include <stdio.h>
int main(void)
{
unsigned u = 100;
int n;
for(n = 32768; n; n = n >> 1)
if(u & n)
printf("1 ");
else
printf("0 ");
printf("\n");
return 0;
}
Use bit shift to calculate
#include <stdio.h>
int main(void)
{
int i = 1;
i <<= 3; /* multiply by 2, 3 times */
printf("%d", i);
return 0;
}