Skip to content

Instantly share code, notes, and snippets.

@KittyMac
Created April 1, 2016 03:22
Show Gist options
  • Save KittyMac/2b4a0e573620dbdf44705bc8e729fe1a to your computer and use it in GitHub Desktop.
Save KittyMac/2b4a0e573620dbdf44705bc8e729fe1a to your computer and use it in GitHub Desktop.
C# implementation of atof; replacement when necessary for float.TryPars; approximately 2.4x faster
private float atof(char[] num, ref int index) {
float integerPart = 0;
float fractionPart = 0;
float divisorForFraction = 1;
float sign = 1;
char numIndex;
/*Take care of +/- sign*/
if (num [index] == '-') {
index++;
sign = -1;
} else if (num [index] == '+') {
index++;
}
// integer part
while (true) {
numIndex = num [index++];
if (numIndex >= '0' && numIndex <= '9') {
integerPart = integerPart * 10 + (numIndex - '0');
} else if (numIndex == '.') {
break;
} else {
return sign * (integerPart + fractionPart / divisorForFraction);
}
}
// fraction part
while (true) {
numIndex = num [index++];
if (numIndex >= '0' && numIndex <= '9') {
fractionPart = fractionPart * 10 + (numIndex - '0');
divisorForFraction *= 10;
} else {
if (numIndex == 'E') {
// E part
float ePart = 0;
bool eNegative = false;
if (num [index] == '-') {
index++;
eNegative = true;
} else if (num [index] == '+') {
index++;
}
while (true) {
numIndex = num [index++];
if (numIndex >= '0' && numIndex <= '9') {
ePart = ePart * 10 + (numIndex - '0');
} else {
break;
}
}
float eMult = 10.0f;
while (ePart > 1) {
eMult *= 10.0f;
ePart--;
}
return ( eNegative ?
(sign * (integerPart + fractionPart / divisorForFraction)) / eMult :
(sign * (integerPart + fractionPart / divisorForFraction)) * eMult
);
}
return sign * (integerPart + fractionPart / divisorForFraction);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment