Advertisement
Guest User

Untitled

a guest
Sep 16th, 2014
421
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.38 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdint.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. // Helper method to get the bit of val at a certain position n
  7.  
  8. int get_bit(uint16_t *val, int n) {
  9.   return (*val >> n) & 1;
  10. }
  11.  
  12. void lfsr_calculate(uint16_t *reg) {
  13.  
  14.   /* YOUR CODE HERE */
  15.  
  16.   // Declarations
  17.   int bit;
  18.   // Set the dummy bit equal to XOR of the bits at 16, 14, 13 and 11
  19.   bit = get_bit(reg, 0) ^ get_bit(reg, 2) ^ get_bit(reg, 3) ^ get_bit(reg, 5);
  20.   // Right shift the register by 1
  21.   *reg = *reg >> 1;
  22.   // Set the most significant bit of the register to the dummy bit
  23.   *reg = (*reg & ~(1 << 15)) | (bit << 15);
  24.  
  25. }
  26.  
  27. int main() {
  28.   int8_t *numbers = (int8_t*) malloc(sizeof(int8_t) * 65535);
  29.   if (numbers == NULL) {
  30.     printf("Memory allocation failed!");
  31.     exit(1);
  32.   }
  33.  
  34.   memset(numbers, 0, sizeof(int8_t) * 65535);
  35.   uint16_t reg = 0x1;
  36.   uint32_t count = 0;
  37.   int i;
  38.  
  39.   do {
  40.     count++;
  41.     numbers[reg] = 1;
  42.     if (count < 24) {
  43.       printf("My number is: %u\n", reg);
  44.     } else if (count == 24) {
  45.       printf(" ... etc etc ... \n");
  46.     }
  47.     for (i = 0; i < 32; i++)
  48.       lfsr_calculate(&reg);
  49.   } while (numbers[reg] != 1);
  50.  
  51.   printf("Got %u numbers before cycling!\n", count);
  52.  
  53.   if (count == 65535) {
  54.     printf("Congratulations! It works!\n");
  55.   } else {
  56.     printf("Did I miss something?\n");
  57.   }
  58.  
  59.   free(numbers);
  60.  
  61.   return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement