Eyal K. Eyal K. - 1 year ago 59
C Question

C++: Efficient way to turn part of char array to int

I have a char buffer that contains several integers one after the other without any breaks between them, where the offsets of each separate number are known in advance. For example "1234123123456", where from position [0] to [3] it would be the first number, [4] to [6] the second, and [7] to the end would be the third.

Is there any way to convert these different sections to ints without altering the buffer? Please no usage of std::string since it is inefficient for my purposes.

Answer Source

You can write a simple conversion function like this:

int convert_slice(const char *s, size_t a, size_t b) {
    int val = 0;
    while (a < b) {
       val = val * 10 + s[a++] - '0';
    return val;

int main(void) {
    char buffer[] = "12345678901234567890";

    printf("%d\n", convert_slice(buffer, 0, 4);
    printf("%d\n", convert_slice(buffer, 4, 6);
    printf("%d\n", convert_slice(buffer, 6, 11);
    printf("%d\n", convert_slice(buffer, 11, 20);

    return 0;

Will produce:


Note that I use 2 index arguments, the first is included and the second is excluded. This is more consistent with C and C++ practices. You could also use a more classic C++ API such as int convert_slice(const char *a, const char *b);