问题描述:

If I read the contents of the buffer into a string, how do i parse it in C?

lets say, I wish to parse a string in the following format:

store first 16 bits in an integer,

store next 32 bits in another integer,

store remaining string data as hex.

网友答案:

Basically you want something like the following (don't forget validations)

int first = (text[0] << CHAR_BIT) + text[1];
int second = (text[2] << (CHAR_BIT * 3)) +
             (text[3] << (CHAR_BIT * 2)) +
             (text[4] << CHAR_BIT) +
             text[5];
char *rest = text + 6;
网友答案:

Assumptions:
int1 & int2 integers are the same endian as in the buffer.
s alignment may not meet int needs.

#include <stdint.h>
void codeara_parse(const char *s, int16_t *int1, int32_t *int2, int8_t **rest) {
  memcpy(int1, &s[0]           , sizeof *int1);
  memcpy(int2, &s[sizeof *int1], sizeof *int2);
  *rest = &s[sizeof *int1 + sizeof *int2];
}

Otherwise OP needs to specify the endian-ness of the buffer.

相关阅读:
Top