• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 214
  • Last Modified:

Convert array of bytes to signed longs

I have program that calls on a library function to pull data off of a tape.  The function puts the data in a variable length unsigned char array where every 4 bytes represents a signed long integer.  How do I go about converting each 4 byte segment into signed longs (decimal values), and then back to a second unsigned char array (for testing purposes)?

Thanks.
0
mtvann
Asked:
mtvann
  • 2
  • 2
1 Solution
 
sunnycoderCommented:
Hi mtvann,

From the question it appears that there is no conversion involved ... bit sequence would be the same in both the cases ... If that is the case, then simply use a pointer to traverse the array ... Traversing signed long * and unsigned char * would achieve what you desire.

unsigned char buffer[BUFFER_LEN] = { /*your data */ };
...
unsigned char * ptr1 = buffer;
signed long * ptr2 = buffer;

while ( ptr1 < buffer+ BUFFER_LEN)
{
       //process *ptr1
       ptr1++;
}

//similar loop for ptr2

Cheers!
sunnycoder
0
 
daohailamCommented:
IMO, you have to verify byte-order of the source data & your system first. Depend on byte-order (Big Endian or Little Endian), we will have the correct way to convert.  If they are the same byte-order, you can use following code:

unsigned char *data = getdatafromtape();
long *lp = (long *)data;

for (i = 0; i < N; i++)
   printf("%ld\n", *lp++);


HTH
0
 
mtvannAuthor Commented:
Hi daohailam,
   Byte order is the same... In the for loop, is N the length of data, or is it (for a 4 byte long) the length of data/4?

Thanks
mtvann
0
 
daohailamCommented:
N = length of data / 4

0
 
sunnycoderCommented:
For any given type, it would be

< BufferLength / sizeof(type)
If your buffer length was 6 and size of long is 4, two bytes would remain unread

If there is some remainder left, you would not be able to access it using the same pointer in the same loop. If you have to access those bytes, then you would have to copy them into a variable of that type. e.g. for longs

//End of loop ... ptr2 points to end of buffer - last few bytes remain which cannot be accessed since they would cause the
//loop to read beyond the end of array

if (BufferLength%sizeof (long))
{
       long k = strtol (ptr2, 0, 10);
        //process value in variable k
}

add error checking as required.
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now