Another option for using strings to split:
#include <stdio.h> #include <string.h> #include <stdlib.h> int split( int val, int *top, int *bot ) { char tmp[23]; // should be large enough to hold a 64-bit decimal integer // plus sign plus 0 terminator char low[12] = {0}; char high[12] = {0}; if ( val < 0 ) val = -val; sprintf( tmp, "%d", val ); if ( strlen( tmp ) % 2 ) return 0; strncpy( low, tmp, strlen( tmp ) / 2 ); strncpy( high, tmp + strlen( tmp ) / 2, strlen( tmp ) / 2 ); *top = (int) strtol( low, NULL, 10 ); *bot = (int) strtol( high, NULL, 10 ); return val; } int main( int argc, char **argv ) { if ( argc < 2 ) { fprintf( stderr, "USAGE: %s integer_value_with_even_number_of_digits\n", argv[0] ); exit( 0 ); } int val = (int) strtol( argv[1], NULL, 10 ); int lo, hi; if ( split( val, &lo, &hi ) ) printf( "val: %d, lo: %d, hi: %d\n", val, lo, hi ); else fprintf( stderr, "USAGE: %s integer_value_with_even_number_of_digits\n", argv[0] ); exit( 0 ); }
Some run spaces:
[fbgo448@n9dvap997]~/prototypes/splitter: ./splitter 1 USAGE: ./splitter integer_value_with_even_number_of_digits [fbgo448@n9dvap997]~/prototypes/splitter: ./splitter 12 val: 12, lo: 1, hi: 2 [fbgo448@n9dvap997]~/prototypes/splitter: ./splitter -12 val: -12, lo: 1, hi: 2 [fbgo448@n9dvap997]~/prototypes/splitter: ./splitter -123 USAGE: ./splitter integer_value_with_even_number_of_digits [fbgo448@n9dvap997]~/prototypes/splitter: ./splitter -1234 val: -1234, lo: 12, hi: 34 [fbgo448@n9dvap997]~/prototypes/splitter: ./splitter 12345678 val: 12345678, lo: 1234, hi: 5678 [fbgo448@n9dvap997]~/prototypes/splitter: ./splitter -1234567890 val: -1234567890, lo: 12345, hi: 67890 [fbgo448@n9dvap997]~/prototypes/splitter: ./splitter 012 val: 12, lo: 1, hi: 2 [fbgo448@n9dvap997]~/prototypes/splitter: ./splitter 00123456 val: 123456, lo: 123, hi: 456 [fbgo448@n9dvap997]~/prototypes/splitter: ./splitter 001234567 USAGE: ./splitter integer_value_with_even_number_of_digits
You did not indicate whether the values should be positive or not, or leading zeros are counted against the number of digits (since it is read as an integer value, not a string, there are no leading zeros after the conversion).
For me, this code has the power of simplicity. We, in fact, consider the number as a string of numbers to divide the middle, so (at least in my opinion) using string operations seemed the simplest. In terms of performance, this should not be slower than using log to get numbers and scroll through them.