Last active
July 5, 2023 03:40
-
-
Save hchasens/52ba6c1f0c6ccadfbb45cc0978e960de to your computer and use it in GitHub Desktop.
C one-line macro that finds the length of an int `x`. [E.g. lenOfInt(12345) will return 5]
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
/** | |
* Needs <math.h> to work as it calls the ceil() function. | |
* Doesn't work on neg ints without modification [see line x for example] | |
* Returns a short to reduce spatial complexity; modify to cast as int if needed. | |
* | |
**/ | |
#include <stdlib.h> | |
#include <math.h> | |
#define lenOfInt(x) ((x) == 0 ? 1 : (int)(log10(abs(x)) + 1)) | |
// example code driver | |
#include <stdio.h> | |
int main() | |
{ | |
printf("%d\n", lenOfInt(9334)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment