Welcome to the Second Life Forums Archive

These forums are CLOSED. Please visit the new forums HERE

Float2Hex safe transport for floats without need of a parser

Strife Onizuka
Moonchild
Join date: 3 Mar 2004
Posts: 5,887
01-25-2006 03:04
SL support the C99 style for encoding floats as a hex string.
This method for encoding provides many advantages, 1) the data is stored in a memory in such a way to conserve it 2) the function is fast with a speed of 0.11 seconds per iteration. The number doesn't effect the speed.

This function could be better writen to concerve memory by adding a decimal point into the string for numbers around zero, this could free up a couple of bytes. It is a low priority. Doing so would come at quite a bit of expense in speed. Also any gaining those couple extra bytes, many more bytes would be wasted in bytecode. There are som small optimizations that can be made. The zero stripper is needed or "p" is ignored.

CODE

string hexc="0123456789ABCDEF";//faster

string Float2Hex(float a)
{// Copyright Strife Onizuka, 2006, LGPL, http://www.gnu.org/copyleft/lesser.html
if(a)
{
float b = llFabs(a);//logs don't work on negatives.
string f = "p";
integer c = llFloor(llLog(b) / 0.69314718055994530941723212145818);//floor(log2(b))
if(c > 127) c = 127;//catch fatal rounding error in exponent.
integer d = (integer)((b / (float)("0x1p"+(string)c)) * 0x1000000);//shift up into integer range
while(!(d & 0xf))
{//strip extra zeros off before converting or they break "p"
d = d >> 4;
c+=4;
}
do
f = llGetSubString(hexc,15&d,15&d) + f;
while(d = d >> 4);
if(a < 0)
return "-0x" + f +(string)(c - 24);
return "0x" + f +(string)(c - 24);
}
return "0";//zero would hang the zero stripper.
}
_____________________
Truth is a river that is always splitting up into arms that reunite. Islanded between the arms, the inhabitants argue for a lifetime as to which is the main river.
- Cyril Connolly

Without the political will to find common ground, the continual friction of tactic and counter tactic, only creates suspicion and hatred and vengeance, and perpetuates the cycle of violence.
- James Nachtwey
Nada Epoch
The Librarian
Join date: 4 Nov 2002
Posts: 1,423
Discussion Thread
01-25-2006 14:24
/54/fb/84483/1.html
_____________________
i've got nothing. ;)