Lkaf Temravet
Lkaf Temravet

Reputation: 993

how to use sscanf with speficied length

I want to convert an array of unsigned char to integer using sscanf, but convert only 3 characters

unsigned char buffer[] = "FF34567A9";
sscanf((const char *)buffer, "%x %x %x", &x, &y, &z);

result expected for x = FF3, y = 456 z = 7A9

Upvotes: 0

Views: 259

Answers (2)

imswapy
imswapy

Reputation: 132

In general , you can do this in loop for multiple values like this

int arr[MAXN];
unsigned char* tmp = buffer;
for ( int i = 0; sscanf((const char*)tmp, "%3x", &arr[i]); ++i, tmp += 3 );

Upvotes: 1

deviantfan
deviantfan

Reputation: 11424

GIven that you don't seems to know the type of your variable yourself (eg. declaring a constant without const, at least before the edit, just to cast it later to const, and the unsigned thing) I'm recommending std::string:

std::string s = "123456789";
s = s.substr(0, 3);
int x = std::stoi(s);

About your edit:

std::string s = "123456789";
int x = std::stoi(s.substr(0, 3));
int y = std::stoi(s.substr(3, 3));
int z = std::stoi(s.substr(6, 3));

Upvotes: 0

Related Questions