Skip to content

Instantly share code, notes, and snippets.

@hchasens
Last active July 2, 2023 08:40
Show Gist options
  • Save hchasens/7fcbc242c93953e8a971c73b45d9a422 to your computer and use it in GitHub Desktop.
Save hchasens/7fcbc242c93953e8a971c73b45d9a422 to your computer and use it in GitHub Desktop.
C one-line macro that finds the digit of a int at place `i`. [E.g. getDigitAt(12345, 2) will return 3]
/**
* Indexing starts at zero from the right.
* Needs <math.h> to work as it calls the pow() function.
* Can work on negative integers, but the returned number will be negative (aside from zero since it's unsigned)
* Can be fixed by using abs() function and including <stdlib.h> [See line 12 for example]
* Attempting to use an out-of-range index will return a zero [e.g. getDigitAt(1234, 10) will return 0].
* This can be fixed with a ternary conditional and may be added in future versions of this snippet.
**/
#include <math.h>
#define getDigitAt(x, i) (int)floor(x%(int)pow(10,i+1)/(int)(pow(10,i+1)/10))
// modified for negatives -- must include <stdlib.h>
// #include <stdlib.h>
// #define getDigitAt(x, i) abs((int)floor(x%(int)pow(10,i+1)/(int)(pow(10,i+1)/10)))
// example code driver
#include <stdio.h>
int main()
{
int x = 1234567890;
for(int i = 0; i < 10; i++)
printf("%d\n", getDigitAt(x, i));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment