I had a very similar question - https://math.stackexchange.com/questions/120459/how-to-find-the-first-and-last-n-2-digits-from-an-n-digit-number
In your case, if it is always a 4
-digit number and you always need the first 2
-digits, then as others suggested X/100
would be the best thing to do.
But if you need n/2
-digits from an n
-digit integer, say X
, then you may have to use the following:
first n/2 digit (for even value of n) = X / 10^(n/2)
first n/2 digit (for odd value of n) = X / 10^((n+1)/2)
last n/2 digit (for even value of n) = X - [first n/2 digit * pow(10, n/2)]
last n/2 digit (for odd value of n) = X - [first n/2 digit * pow(10, (n+1)/2)]
The following may be an overkill, but you may be looking for something like this!
int getn(int num)
{
return (int) log10(num) + 1;
}
void gethalfs(int num, int * first, int * last)
{
int n, po;
if (num == 0) return;
n = getn(num);
/* Here you can calculate the value of po based on whether n is even or odd */
po = (int) pow(10, n/2);
*first = num / po;
*last = num - *first * po;
return;
}
In order to get the number of digits in a given integer i.e. n
in the above case, you may look at the following possible methods - count number of digits - which method is most efficient?
Hope this helps!