Skip to content

Instantly share code, notes, and snippets.

@octalmage
Created July 18, 2015 15:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save octalmage/2b873e2b50695cda56d8 to your computer and use it in GitHub Desktop.
Save octalmage/2b873e2b50695cda56d8 to your computer and use it in GitHub Desktop.
C padding code - Pad a hex value with leading zeros.
#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