Last active
November 12, 2022 16:48
-
-
Save CarloCattano/ab13f34d70d1f188232bde2be9d7913b to your computer and use it in GitHub Desktop.
Playing with bit shifting and some other bitwise operators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Carlo Cattano - bitshifting experiments */ | |
#include <unistd.h> | |
#include <stdlib.h> | |
#include <stdio.h> | |
#define T_INTERVAL 30000 // 30 milliseconds | |
void ft_putchar(char c) | |
{ | |
write(1, &c, 1); | |
} | |
void bin(unsigned n) //Prints the int in binary | |
{ | |
unsigned i; | |
for (i = 1 << 31; i > 0; i = i / 2) | |
(n & i) ? ft_putchar('1') : ft_putchar('0'); | |
} | |
void roll_up_down(int shift) //shifts to left and right the whole 32 bit range | |
{ | |
int i = 0; | |
while (++i < 31) | |
{ | |
shift = shift << 1; | |
bin(shift); | |
usleep(T_INTERVAL); | |
printf(" %d \n", shift); | |
} | |
while (i-- > 1) | |
{ | |
shift = shift >> 1; | |
bin(shift); | |
usleep(T_INTERVAL); | |
printf(" %d \n", shift); | |
} | |
} | |
void un_roll_up_down(unsigned int i, unsigned int shift) //shifts to left and right the whole 32 bit range | |
{ | |
printf("\n--------------\nUnsigned INT\n------\n"); | |
while (++i < 31) | |
{ | |
shift = shift << 1; | |
bin(shift); | |
usleep(T_INTERVAL); | |
printf(" %d \n", shift); | |
} | |
while (i-- > 1) | |
{ | |
shift = shift >> 1; | |
bin(shift); | |
usleep(T_INTERVAL); | |
printf(" %d \n", shift); | |
} | |
} | |
void flip_flop(int n) | |
{ | |
printf("\n--------------\nFlip and shift\n------\n"); | |
int i = 64; | |
int floppy_start = n; //d 1431655765 b 1010101010101010101010101010101 | |
while (i-- > 0) | |
{ | |
if(!(i % 4)) | |
floppy_start = ~floppy_start; //flips 1's to 0's or 0's to 1's | |
if(!(i % 2)) | |
floppy_start = floppy_start >> 2; | |
bin(floppy_start); | |
usleep(T_INTERVAL); | |
printf(" %d \n", floppy_start); | |
} | |
} | |
int main() { | |
int shift; | |
shift = 1; | |
roll_up_down(shift); | |
shift = 2; | |
roll_up_down(shift); | |
roll_up_down(shift); | |
flip_flop(1431655765); | |
unsigned int ui = 1; // test with unsigned ints | |
unsigned int ushift = 1; | |
un_roll_up_down(ui , ushift); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment