Endianness fix (not depending on the host endianness)

This commit is contained in:
Marko Viitanen 2012-06-06 11:59:02 +03:00
parent e202eb2f91
commit aaa6f59cef
2 changed files with 21 additions and 11 deletions

View file

@ -57,6 +57,7 @@
<Link> <Link>
<SubSystem>Console</SubSystem> <SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation> <GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>Ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link> </Link>
</ItemDefinitionGroup> </ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">

View file

@ -16,6 +16,12 @@
#include <math.h> #include <math.h>
#include <string.h> #include <string.h>
#include <stdarg.h> #include <stdarg.h>
/* for hton */
#ifdef WIN32
#include <Winsock2.h>
#else
#include <net/hton.h>
#endif
#include "global.h" #include "global.h"
#include "bitstream.h" #include "bitstream.h"
@ -133,6 +139,8 @@ void bitstream_put(bitstream* stream, uint32_t data, uint8_t bits)
stream->cur_bit = 0; stream->cur_bit = 0;
if(stream->cur_byte==32) if(stream->cur_byte==32)
{ {
//We only have bytes 0..31
stream->cur_byte--;
//Flush data out //Flush data out
bitstream_flush(stream); bitstream_flush(stream);
} }
@ -166,6 +174,7 @@ void bitstream_flush(bitstream* stream)
* SAVE DATA TO OUTPUT * SAVE DATA TO OUTPUT
*/ */
int i,j; int i,j;
uint32_t correct_endian;
if(stream->output) if(stream->output)
{ {
if(stream->cur_byte) if(stream->cur_byte)
@ -183,25 +192,25 @@ void bitstream_flush(bitstream* stream)
{ {
if(stream->cur_byte) if(stream->cur_byte)
{ {
//memcpy((uint8_t*)&stream->buffer[stream->buffer_pos],(uint8_t*)stream->data,stream->cur_byte*4); /* Handle endianness issue */
for(i = 0; i < stream->cur_byte+1; i++)
for(i = 0,j=3; i < stream->cur_byte*4; i++,j--)
{ {
if(j == -1) j = 3; /* "network" is big-endian */
stream->buffer[stream->buffer_pos+i] = ((uint8_t*)stream->data)[((i>>2)<<2)+j]; correct_endian = htonl(stream->data[i]);
memcpy((uint8_t*)&stream->buffer[stream->buffer_pos],&correct_endian,4);
stream->buffer_pos += 4;
} }
stream->buffer_pos += stream->cur_byte*4;
} }
if(stream->cur_bit>>3) if(stream->cur_bit>>3)
{ {
memcpy((uint8_t*)&stream->buffer[stream->buffer_pos],(uint8_t*)&stream->data[stream->cur_byte],stream->cur_bit>>3); correct_endian = htonl(stream->data[stream->cur_byte]);
memcpy((uint8_t*)&stream->buffer[stream->buffer_pos],&correct_endian,stream->cur_bit>>3);
stream->buffer_pos += stream->cur_bit>>3; stream->buffer_pos += stream->cur_bit>>3;
} }
} }
//Stream flushed, zero out the values //Stream flushed, zero out the values
bitstream_init(stream); bitstream_init(stream);
} }
/* /*