Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the integer value of a char in C++?

I want to take the value stored in a 32 bit unsigned int, put it into four chars and then store the integer value of each of these chars in a string.

I think the first part goes like this:

char a = orig << 8;
char b = orig << 8;
char c = orig << 8;
char d = orig << 8;
like image 280
Clayton Avatar asked Nov 29 '22 05:11

Clayton


2 Answers

If you really want to extract the individual bytes first:

unsigned char a = orig & 0xff;
unsigned char b = (orig >> 8) & 0xff;
unsigned char c = (orig >> 16) & 0xff;
unsigned char d = (orig >> 24) & 0xff;

Or:

unsigned char *chars = (unsigned char *)(&orig);
unsigned char a = chars[0];
unsigned char b = chars[1];
unsigned char c = chars[2];
unsigned char d = chars[3];

Or use a union of an unsigned long and four chars:

union charSplitter {
    struct {
        unsigned char a, b, c, d;
    } charValues;

    unsigned int intValue;
};

charSplitter splitter;
splitter.intValue = orig;
// splitter.charValues.a will give you first byte etc.

Update: as friol pointed out, solutions 2 and 3 are not endianness-agnostic; which bytes a, b, c and d represent depend on the CPU architecture.

like image 93
Ates Goral Avatar answered Dec 04 '22 21:12

Ates Goral


Let's say "orig" is a 32bit variable containing your value.

I imagine you want to do something like this:

unsigned char byte1=orig&0xff;
unsigned char byte2=(orig>>8)&0xff;
unsigned char byte3=(orig>>16)&0xff;
unsigned char byte4=(orig>>24)&0xff;

char myString[256];
sprintf(myString,"%x %x %x %x",byte1,byte2,byte3,byte4);

I'm not sure this is always endian correct, by the way. (Edit: indeed, it is endian correct, since bitshift operations shouldn't be affected by endianness)

Hope this helps.

like image 30
friol Avatar answered Dec 04 '22 23:12

friol