We help IT Professionals succeed at work.

# Convert array of bytes to signed longs

on
Medium Priority
230 Views
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.
Comment
Watch Question

## View Solution Only

CERTIFIED EXPERT
Top Expert 2006

Commented:
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

Commented:
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

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
Commented:
N = length of data / 4

Not the solution you were looking for? Getting a personalized solution is easy.

CERTIFIED EXPERT
Top Expert 2006

Commented:
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
}

##### Thanks for using Experts Exchange.

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile