Advertisement
atm959

dec2bin.c

Jan 27th, 2023
952
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.06 KB | None | 0 0
  1. //dec2bin - A program to convert a decimal number to binary
  2. //Made by atm959 on January 27th, 2023
  3.  
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. #include <string.h>
  7.  
  8. typedef unsigned char bool;
  9. #define false 0
  10. #define true 1
  11.  
  12. void dec2bin(char* res, unsigned long long num, bool withSeparaters, bool withNumbers){
  13.     unsigned long long mask = 0x8000000000000000;
  14.    
  15.     for(int i = 0; i < 64; i++){
  16.         if(withSeparaters){
  17.             if((i % 8) == 0){
  18.                 strcat(res, "|");
  19.             }
  20.         }
  21.        
  22.         unsigned long long bit = num & mask;
  23.         strcat(res, bit ? "1" : "0");
  24.         mask = mask >> 1;
  25.     }
  26.    
  27.     if(withNumbers){
  28.         strcat(res, "\n");
  29.        
  30.         unsigned char bitNum = 64;
  31.         for(int i = 0; i < 64; i++){
  32.             if(((i % 8) == 0)){
  33.                 if(withSeparaters){
  34.                     strcat(res, "|");
  35.                 }
  36.                
  37.                 char numStr[3];
  38.                 sprintf(numStr, "%d", bitNum);
  39.                 strcat(res, numStr);
  40.                
  41.                 int numSpaces = 8 - strlen(numStr);
  42.                 for(int i = 0; i < numSpaces; i++){
  43.                     strcat(res, " ");
  44.                 }
  45.                
  46.                 bitNum -= 8;
  47.             }
  48.         }
  49.     }
  50. }
  51.  
  52. int main(int argc, char** argv){
  53.     if(argc < 2){
  54.         printf("Usage: dec2bin [num] [options]\n");
  55.         printf("\tnum - The number to convert to binary\n");
  56.         printf("\toptions - can be one or both of these, with a space between them:\n");
  57.         printf("\t\t-n - Show bit numbers under the bits\n");
  58.         printf("\t\t-s - Have separaters between every 8 bits\n");
  59.     } else {
  60.         bool withNumbers = false;
  61.         bool withSeparaters = false;
  62.         if(argc > 2){
  63.             for(int i = 2; i < argc; i++){
  64.                 if(strcmp(argv[i], "-n") == 0) withNumbers = true;
  65.                 if(strcmp(argv[i], "-s") == 0) withSeparaters = true;
  66.             }
  67.         }
  68.        
  69.         unsigned long long num = atoi(argv[1]);
  70.        
  71.         char binStr[73*2];
  72.         strcpy(binStr, "");
  73.         dec2bin(binStr, num, withSeparaters, withNumbers);
  74.         printf("%s\n", binStr);
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement