• C

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.
mtvannAsked:
Who is Participating?
 
daohailamConnect With a Mentor Commented:
N = length of data / 4

0
 
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
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.