1

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.

3
  • 5
    C is not C++ is not C. Pick one language. Commented Aug 18, 2016 at 11:29
  • 1
    I'm programming in C++, but a plain C answer would also help me here, since they are usually more efficient Commented Aug 18, 2016 at 11:31
  • 1
    @EyalK. - "usually more efficient" is usually nonsense. Commented Aug 18, 2016 at 13:04

2 Answers 2

4

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:

1234
56
78901
234567890

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Although this will do funny stuff on a string like "1234ab+cd/89". So you might want to do some error handling, depending where you are getting the strings from.
Error handling would cost too much since I need this to run on a tight loop. I'm getting the strings from a file that is almost guaranteed to be OK, so I'd rather risk the small chance of errors vs. the runtime difference
1

One clean way to do this without writing your own parsing code or making temporary copies is to use sscanf:

sscanf(src+start_offset, "%4d", &result);

If the length of the field (4 in the example) is not constant, though, you'll need either snprintf to construct a format string to pass to sscanf, or an array of possible format strings for the sizes you need.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.