Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ENDIANESS 1

Status
Not open for further replies.

JGSH

Programmer
Feb 23, 2003
6
US
hey all,

If my machine is a different endianess from the file I'm reading, how do I go about switching the bytes?

Ex:
machine = little endian
file = big endian

file
0001

If i read this file normally, as an unsigned int, then I will come up with the value 4, because it will read it as 0100. I need it to read as 0001 and come up with the value 1.

Any suggestions?

thanks,
Jon
 
Here are the guide lines

char (no byteswap required)
// all types above 1 byte require byteswapping

You must know the size of the type before byteswapping

Here is a simple byteswap function. It works because I use it :)

void byteswap(void* ptr,size_t size)
{
char* bsptr = (char*)ptr;

for(int i = 0,j=size-1;i<j;i++,j--)
{
bsptr^=bsptr[j]^=bsptr^=bsptr[j];
}
}

You call it as

int x = (value read in from file)
byteswap(x,sizeof(x));

Hope that helps

Matt
 
Code:
void byteswap(void* ptr,size_t size)
{
	char* bsptr = (char*)ptr;

	for(int i = 0,j=size-1;i<j;i++,j--)
	{
		bsptr[i]^=bsptr[j]^=bsptr[i]^=bsptr[j];
	}
}
sorry bout that :p

Matt
 
sorry again... call it as

byteswap(&x,sizeof(x));

But I'm sure you figured that one out ;-)

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top