# byte to long

• 10-21-2001
Unregistered
byte to long
ok i have a byte buffer

byte buf[16]; in which i have stored longs.

now how do i add the longs in it and get the total in another long?
or in other words how would i read a long out of it?
• 10-22-2001
gliptic
You can't have longs in a byte buffer unless you use 4 byte slots for every long. In your case, you could store 4 longs in the array. Add them together using:

long total=0;
for(long i = 0; i < 4; i++)
{
total += (long*)(buf)[i];
}

I think I got it right.
• 10-22-2001
Unregistered
i came across this but i wasn't sure. becuase

lets say i have a long thats something like this

00010010 01011010 10010010 10010010

when i save it to a
byte buf[4]
it then splites into four parts. if i add each byte that is buf[0] +buf[1] +buf[2] +buf[3] would not the answer be different?

like:
buf[0] = 00010010
buf[0] = 01011010 +
buf[0] = 10010010 +
buf[0] = 10010010 +
=================
11001 0000 ??? not the same ???
• 10-22-2001
gliptic
Of course it would be different. That's because you are adding all the bytes in the long together. If you want to read the long you just type: *(long*)buf .
• 10-22-2001
Unregistered
sorry could you give me an example?

lets say i have a

byte buf[16]; with four longs in it.

long total=0;
for(long i = 0; i < 4; i+=4 )
{

total += * (long*)(buf)[i];

}
• 10-22-2001
gliptic
No, this one:

long total=0;
for(long i = 0; i < 4; i++)
{
total += (long*)(buf)[i];
}

Think of the byte array as what it is, a byte array!
There are 16 bytes in it. In this code, we are treating the array just as it was a long array with four elements.

Sorry, I don't have time to write more now...
• 10-22-2001
Unregistered
thanks for your help, but i get this error

'+=' : illegal, right operand has type 'long *'

when using above, and if i remove the * the results still wrong?
• 10-22-2001
zen
Here's how you'd do it with a byte array holding two longs -

Code:

```#include <iostream> using namespace std; typedef unsigned char byte; int main () {           byte buf[8];                 long a=10,b=25;         //Put two longs in byte array         *(long*)buf = a;         *(long*)&buf[4]=b;                         long total=0;         for(int i = 0; i < 8; i+=4)         {         total += *(long*)&buf[i];         }         cout << total;                 return 0; }```
• 10-22-2001
Salem
```byte buf[16]; long *lbuff = (long *)buff; for ( i = 0 ; i < 4 ; i++ ) {     sum += lbuff[i]; }```