I had tried to do it myself but failed (I am tempted to do it again for learning but just need it for an example program). Essentially I wish to represent a binary number but padded of course to the nearest byte with 0‘s so I found a function on another question here:
char * string_pad(char * string, size_t padlen, char * pad) {
size_t lenstring = strlen(string);
size_t lenpad = strlen(pad);
char * padded = (char*)malloc(lenstring + lenpad + 1);
strncpy(padded, string, lenstring); /* copy without '\0' */
padded += lenstring; /* prepare for first append of pad */
for(padlen += 1; padlen > 0; padlen--, padded += lenpad)
strncpy(padded, pad, lenpad);
*padded = '\0';
return padded;
}
I am calling it like this:
printf("Test: %s\n", string_pad(dec2bin(~myInt), 32, "0"));
Unfortunately it prints “Test: ” but nothing else. My dec2bin returns a simple char pointer by the way if you need to know.
What seems to be causing it to do nothing?
Why does this function accept char* pad and not char pad so I can do just pad it with ‘0’, will “0” work too or does it add a null terminator screwing it up or something?
EDIT: Or can somebody provide a simple example (or what I need to do what) to pad left for this? This snippet does not appear to be all that good..
I was thinking of creating a chararray initialized to zero, then copying the binary after that, but how to make it work escaped me..
“padded” points to the end of the string when you are returning it.