Last active
April 8, 2020 04:35
-
-
Save bshambaugh/8788cdb6644e235c510dc7cb2f4b3786 to your computer and use it in GitHub Desktop.
8bit hex number to binary number
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
/* This code converts a 8bit hex number to a string representation of a binary number */ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
// variables to convert hex to binary in reverse order | |
int number; | |
int data[9] = {1,2,4,8,16,32,64,128,255}; // in the future (perhaps) use 2 ^ n - 1 , I need to allocate a buffer for this... | |
int count; | |
int dummy; | |
char *ptrb, *pb; | |
int main ( void ) | |
{ | |
// read in a hex number here... | |
printf("enter a hexidecimal number in the form XxXX\n"); | |
scanf("%X", &number); | |
// this needs to have error checking | |
dummy = number; | |
ptrb = ( char * ) malloc(12 * sizeof(char)); | |
if ( ptrb == NULL) | |
{ | |
printf( "Not enough memory to allocate buffer\n"); | |
return 1; | |
} | |
pb = ptrb; | |
*pb++ = '0'; | |
*pb++ = 'b'; | |
// the count needs to be tied to the memory length ? | |
for(count=7; count >= 0; count--) { | |
if((data[count] - dummy) > 0 ) { | |
*pb++ = '0'; | |
// add a line of code to push 0 to the string | |
} else { | |
dummy = dummy - data[count]; | |
*pb++ = '1'; | |
// add a line of code to push 1 to the string | |
} | |
} | |
*pb = '\0'; | |
printf("number in decimal is: %d\n",number); | |
printf("the number in hex is: %x\n",number); | |
printf("the number in binary is: %s\n",ptrb); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment