SakurasouBusters, The thing with this buffer I made is that you can use it as a file.
First write all your data, then read all of it.
In my example it allocates 1000 bytes on the heap.
Ofc you can use this to store a value at a time, but that was not my intent.
Anyway I solved my problem by doing
1 2 3 4 5 6 7 8
|
bool Buffer::tryWriteFloat(float val)
{
return tryWriteUInt(*(unsigned long*)&val);
}
bool Buffer::tryReadFloat(float& val)
{
return tryReadUInt(*(unsigned long*)&val);
}
|
Where those functions are defined as
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
bool Buffer::tryWriteUInt(unsigned long val)
{
if(RemainingSpace() < 4) return false;
buffer[written ] = (val & 0xff000000) >> 24;
buffer[written + 1] = (val & 0x00ff0000) >> 16;
buffer[written + 2] = (val & 0x0000ff00) >> 8;
buffer[written + 3] = (val & 0x000000ff);
written += 4;
return true;
}
bool Buffer::tryReadUInt(unsigned long& val)
{
if(RemainingData() < 4) return false;
val = 0;
val |= ((unsigned long)buffer[read ]) << 24;
val |= ((unsigned long)buffer[read + 1]) << 16;
val |= ((unsigned long)buffer[read + 2]) << 8;
val |= ((unsigned long)buffer[read + 3]);
read += 4;
return true;
}
|
And I did the same with double and unsigned long long.
From some reason the compilers really don't like it when you use float/double as a char[]. And using optimizations -o2 or -o3 even causes errors.
The problem I was looking to solve with this buffer is that I had a lot of numbers to send over a socket and I didn't want to use the send function every time.
At the moment I am doing
send(mSocket, (char*)&theNumber, 8, 0);
which works great, but I end up with a ton of calls to send function for literally few bytes at a time.