Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //dec2bin - A program to convert a decimal number to binary
- //Made by atm959 on January 27th, 2023
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- typedef unsigned char bool;
- #define false 0
- #define true 1
- void dec2bin(char* res, unsigned long long num, bool withSeparaters, bool withNumbers){
- unsigned long long mask = 0x8000000000000000;
- for(int i = 0; i < 64; i++){
- if(withSeparaters){
- if((i % 8) == 0){
- strcat(res, "|");
- }
- }
- unsigned long long bit = num & mask;
- strcat(res, bit ? "1" : "0");
- mask = mask >> 1;
- }
- if(withNumbers){
- strcat(res, "\n");
- unsigned char bitNum = 64;
- for(int i = 0; i < 64; i++){
- if(((i % 8) == 0)){
- if(withSeparaters){
- strcat(res, "|");
- }
- char numStr[3];
- sprintf(numStr, "%d", bitNum);
- strcat(res, numStr);
- int numSpaces = 8 - strlen(numStr);
- for(int i = 0; i < numSpaces; i++){
- strcat(res, " ");
- }
- bitNum -= 8;
- }
- }
- }
- }
- int main(int argc, char** argv){
- if(argc < 2){
- printf("Usage: dec2bin [num] [options]\n");
- printf("\tnum - The number to convert to binary\n");
- printf("\toptions - can be one or both of these, with a space between them:\n");
- printf("\t\t-n - Show bit numbers under the bits\n");
- printf("\t\t-s - Have separaters between every 8 bits\n");
- } else {
- bool withNumbers = false;
- bool withSeparaters = false;
- if(argc > 2){
- for(int i = 2; i < argc; i++){
- if(strcmp(argv[i], "-n") == 0) withNumbers = true;
- if(strcmp(argv[i], "-s") == 0) withSeparaters = true;
- }
- }
- unsigned long long num = atoi(argv[1]);
- char binStr[73*2];
- strcpy(binStr, "");
- dec2bin(binStr, num, withSeparaters, withNumbers);
- printf("%s\n", binStr);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement