Facebook
From firaanki, 2 Weeks ago, written in C.
Embed
Download Paste or View Raw
Hits: 111
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define BITMASK 0x3FF // 0b1111111111 in binary represents the last 10 bits
  5.  
  6. char* last10BitsToString(unsigned short num) {
  7.     // Apply bitmask to get the last 10 bits
  8.     unsigned short last10Bits = num & BITMASK;
  9.  
  10.     // Allocate memory for the string representation
  11.     char* str = (char*)malloc(11 * sizeof(char)); // 10 bits + '�'
  12.  
  13.     if (str == NULL) {
  14.         printf("Memory allocation failed.n");
  15.         exit(1);
  16.     }
  17.  
  18.     // Convert the last 10 bits to string
  19.     int i;
  20.     for (i = 0; i < 10; i++) {
  21.         str[9 - i] = (last10Bits & (1 << i)) ? '1' : '0';
  22.     }
  23.     str[10] = '�'; // Null-terminate the string
  24.  
  25.     return str;
  26. }
  27.  
  28. int main() {
  29.     unsigned short num = 12345; // Example unsigned short
  30.     char* str = last10BitsToString(num);
  31.     printf("Last 10 bits of %u in binary: %sn", num, str);
  32.     free(str); // Don't forget to free the allocated memory
  33.     return 0;
  34. }