c++ question

puffpio

Golden Member
Dec 21, 1999
1,664
0
0
I have an int which is 4 bytes long

I want to now get the 4 individual bytes and add them together as if they were 1 byte ints or something...overflows get neglected

so if I had

0x1AD4270F as an integer, I would want it to be

1A + D4 + 27 + 0F (but just chopping off any overflow)

can I take a pointer to a char, set it equal to the address of the integer, and just read all 4 bytes?
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
yes. remember that a char is signed by default (if no "unsigned" specifier), with a range of -128 ...+127.
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
I would guess you'd use bit operations. But 1. byte order is architecture-dependant, 2. the size of an int is architecture-dependant.

But assuming portability doesn't matter, and this is x86 (little-endian IIRC):

unsigned int foo = make_a_random_int();

Now we want to get the individual bytes from foo and put them in chars.

unsigned int mask = 0xff; // the rightmost 8 bits are on, the leftmost 24 bits are off

unsigned char b1, b2, b3, b4;

b1 = foo & mask;

foo >> 8; // push the bits over 8 places

b2 = foo & mask;

foo >> 8;

etc..

note that I haven't done a whole lot of bit twiddling in C/C++, so this could be a bit off or completely wrong and braindead, but I think it's close ;)
 

puffpio

Golden Member
Dec 21, 1999
1,664
0
0
hey guys, I figured it out.

I made a templatized function so that it would work on arbitrary datatypes.
I then casted the address of the arbitrary data type into an unsigned char*
and looped the sizeof(arbitrary data type) and adding the values all together

thanks!
 

CTho9305

Elite Member
Jul 26, 2000
9,214
1
81
Originally posted by: BingBongWongFooey
I would guess you'd use bit operations. But 1. byte order is architecture-dependant, 2. the size of an int is architecture-dependant.

But assuming portability doesn't matter, and this is x86 (little-endian IIRC):

unsigned int foo = make_a_random_int();

Now we want to get the individual bytes from foo and put them in chars.

unsigned int mask = 0xff; // the rightmost 8 bits are on, the leftmost 24 bits are off

unsigned char b1, b2, b3, b4;

b1 = foo & mask;

foo >> 8; // push the bits over 8 places

b2 = foo & mask;

foo >> 8;

etc..

note that I haven't done a whole lot of bit twiddling in C/C++, so this could be a bit off or completely wrong and braindead, but I think it's close ;)

YUCK!

int foo = getSomeInteger();
union blah {
...int foo;
...unsigned char[4] bar;
}

myfunc() {
...union blah thing;
...thing.foo = getAnInteger();
...cout << "sum: " << thing.bar[0] + thing.bar[1] + thing.bar[2] + thing.bar[3] << endl;
}

alternate:
myfunc() {
...int foo = getAnInteger();
...unsigned char *tmp = &foo;
...int sum = char[0] + char[1] + char[2] + char[3];
...cout << "sum: " << sum << endl;
}