954,506 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

converting byte array to long

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?

jov0708
Newbie Poster
6 posts since Feb 2008
Reputation Points: 10
Solved Threads: 0
 

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;
}

Niek

Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 

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));
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

or use a union

int main()
{
   typedef unsigned char byte ;
   union
   {
     byte buffer[ sizeof(long) ] ;
     long key ;
   };
   // ...
}
vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287
 
key |= (long)(buffer[i]);  //<- this line causes the problem
}

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

Isbuffer 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 buffer( 8, false );

TimeFractal
Newbie Poster
17 posts since Feb 2008
Reputation Points: 36
Solved Threads: 2
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You