i would like to copy the contents of a byte array to a long variable. my code looks like this:

long key = 0;
for (i = 0; i < 8; i++) {
    key <<= 8;
    key |= (long)(buffer[i]);  //<- this line causes the problem

however, when i run the program, there is an error message saying "unable to handle exception". what may have cause this problem?

9 Years
Discussion Span
Last Post by TimeFractal

There's a special function for this: atol()

Here's an example of how to use it:

#include <stdio.h>
#include <stdlib.h>

int main ()
  long li;
  char ch[] = "1100033884"; 
  li = atol (ch);
  return 0;



If buffer contains the binary representation of the long then you can just do a simple assignment. But you need to consider the Big/Little Endean problem if the data comes from another source such as across the internet. long x = *(long *)buffer; or use memcpy

long x;
memcpy(&x, buffer, sizeof(long));

or use a union

int main()
   typedef unsigned char byte ;
     byte buffer[ sizeof(long) ] ;
     long key ;
   // ...
Votes + Comments
key |= (long)(buffer[i]);  //<- this line causes the problem

there is an error message saying "unable to handle exception".

Is buffer declared as a byte array?
unsigned char buffer[8];

Native types don't throw exceptions. What you might be doing is using a vector and accessing an index greater than the vector size. Or, the exception is in another part of the code.

If buffer is a vector you can fix this problem by forcing the creation of a vector of predefined length.
vector<char> buffer( 8, false );

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.