Haris
Haris

Reputation: 14053

Read Int from hex array

I have an input array with hex values,

const unsigned char arr[]={0x20, 0x34, 0x30};

I need to concatenate the values arr[1]---> 0x34 ---> 4 and arr[2]---> 0x30 ---> 0

to an integer variable like,

int val = 40; 

How can I do this efficiently in c++?.

Upvotes: 0

Views: 64

Answers (1)

Eran
Eran

Reputation: 2424

As The Paramagnetic Croissant commented, you can turn the array to a string (null terminated at the very least) and use strtol

Example:

const unsigned char arr[]={0x20, 0x34, 0x30};
string s(reinterpret_cast<const char*>(arr), 3);
int val = strtol(s.c_str(), nullptr, 10);

Upvotes: 1

Related Questions