Int to Byte Arrary problem

Started by
3 comments, last by GanonPhantom 15 years, 9 months ago
Im making my own endian function, and on paper i for the most part think i have it correct, but im having a problem getting my type (an int in this case) into a byte array so i can do the flipping.

template<typename T> T ReverseBytes(T _Variable) {
	unsigned int _VariableSize = sizeof(_Variable);
	char* _VariableBuffer = new char[_VariableSize - 1];
	memcpy(_VariableBuffer,(void*)&_Variable,sizeof(_Variable));

	for(unsigned int x = 0; x < (_VariableSize/2); x++) {
			_VariableBuffer[x] ^= _VariableBuffer[(_VariableSize - 1) - x];
			_VariableBuffer[(_VariableSize - 1) - x] ^= _VariableBuffer[x];
			_VariableBuffer[x] ^= _VariableBuffer[(_VariableSize - 1) - x];
	}

	return (T)_VariableBuffer;
}

Heres my notes on it, and as far as i can see, it should work after i get my variable into the byte array, but for some reason, my byte array is incorrect when i look at it in the debugger. http://pastebin.org/50137
Advertisement
Quote:Original post by GanonPhantom
char* _VariableBuffer = new char[_VariableSize - 1];
You seem to be allocating one less byte than is required.
Also, you're never calling delete on that temporary buffer (memory leak).

You could replace that with this code (which fixes the above two problems):
char _VariableBuffer[sizeof(T)];

[Edited by - Hodgman on July 9, 2008 11:33:00 PM]
1) Why are you doing this? If you really need a consistent byte ordering, you can use something like htonl() to keep everything in network byte order.
2) This is really hacky (and untested), but:
template<class T> T byte_swap(T val){	std::reverse((char*)&val, (char*)&val+ sizeof(T));	return val;}
Im doing it for experience and it would be kinda nice to have a function that dosnt require winsock (which requires windows).
Aight this is solved, here is the code the works, for anyone in the future that wants it, or anyone that uses the search feature on the forums.

template<typename T> T ReverseBytes(T _Variable) {	unsigned int _VariableSize = sizeof(_Variable);	char _VariableBuffer[sizeof(T)];	memcpy((void*)&_VariableBuffer,(void*)&_Variable,_VariableSize);	for(unsigned int x = 0; x < (_VariableSize/2); x++) {			_VariableBuffer[x] ^= _VariableBuffer[(_VariableSize - 1) - x];			_VariableBuffer[(_VariableSize - 1) - x] ^= _VariableBuffer[x];			_VariableBuffer[x] ^= _VariableBuffer[(_VariableSize - 1) - x];	}	memcpy((void*)&_Variable,(void*)&_VariableBuffer,_VariableSize);	return _Variable;}


Thx for the replies guys.

This topic is closed to new replies.

Advertisement