Created
July 18, 2015 15:39
-
-
Save octalmage/2b873e2b50695cda56d8 to your computer and use it in GitHub Desktop.
C padding code - Pad a hex value with leading zeros.
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
#include <stdlib.h> | |
#include <stdio.h> | |
#include <math.h> | |
#include <string.h> | |
int main() | |
{ | |
int hex = 11100; | |
//Get length of hex. | |
int dlen = floor(log10(abs(hex))) + 1; | |
//Find how many leading zeros we need. | |
int dpad = 6 - dlen; | |
//Our final hex code. | |
char fhex[] = "000000"; | |
char shex[7]; | |
//Convert hex to a string. | |
sprintf(shex, "%d", hex); | |
//Copy shex to fhex, using dpad as a memory offset. | |
memcpy(fhex+dpad, shex, dlen); | |
printf("%s" , fhex); | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment