0

For example , 130ABF (Hexadecimal) is equals to 1247935 (Decimal), So my byte array is

 char buf[3] = {0x13 , 0x0A , 0xBF};

and I need to retrieve the decimal value from the byte array.

Below are my sample code:

#include<iostream>
using namespace std;
int main()
{
    char buf[3] = {0x13 , 0x0A , 0xBF};
    int number = buf[0]*0x10000 + buf[1]*0x100 + buf[2];
    cout<<number<<endl;
    return 0;
}

and the result is : (Wrong)

1247679

Unless I change the

char buf[3] = {0x13 , 0x0A , 0xBF};

to

int buf[3] = {0x13 , 0x0A , 0xBF};

then It will get correct result.

Unfortunately, I must set my array as char type, anyone know how to solve this ?

2
  • 1
    Are you aware of endianess? You're assuiming a big endian format actually. Commented Jul 19, 2016 at 8:55
  • 1
    @πάνταῥεῖ Good point, though the way he computes the integer is endianness independant. I'm assuming he means "handwritten hexadecimal representation" Commented Jul 19, 2016 at 9:11

4 Answers 4

7

Define the array as:

unsigned char buf[3];

Remember that char could be signed.

UPDATE: In order to complete the answer, it is interesting to add that "char" is a type that could be equivalent to "signed char" or "unsigned char", but it is not determined by the standard.

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

Comments

1

Array elements will be promouted to int before evaluating. So if your compiler treats char as signed you get next (assuming int is 32-bit):

int number = 19*0x10000 + 10*0x100 + (-65);

To avoid such effect you can declare your array as unsigned char arr[], or use masking plus shifts:

int number = ((buf[0] << 16) & 0xff0000)
           | ((buf[1] <<  8) & 0x00ff00)
           | ((buf[2] <<  0) & 0x0000ff;

2 Comments

If char is signed, the third one will be a large negative number
@M.M Oh, yes. My bad. Thanks!
0

Since your char array is signed, when you want to initialize the last element (0xBF), you are trying to assign 191 to it while the max it can store is 127: a narrowing conversion occurs... A workaround would be the following:

unsigned char[3] = { 0x13, 0x0A, 0xBF };

This will prevent the narrowing conversion. Your compiler should have given you a warning about it.

Comments

0
char buf[3] = {0x13 , 0x0A , 0xBF};
union{
unsigned int ui32;
struct{
    unsigned char ll;
    unsigned char lh;
    unsigned char hl;
    unsigned char hh;
    }splitter;
}combine;
combine.ui32 = 0;
combine.splitter.hl = buf[0];
combine.splitter.lh = buf[1];
combine.splitter.ll = buf[2];

cout << combine.ui32 << endl

This should solve your problem.

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.