My function

Asked by Olaf van der Spek

You might find it interesting. ;)

std::string b2a(long long v, const char* postfix)
{
 int l;
 for (l = 0; v < -9999 || v > 999999; l++)
  v >>= 10;
 char d[32];
 char* w = d;
 if (v > 999)
 {
  l++;
  int b = static_cast<int>((v & 0x3ff) * 100 >> 10);
  v >>= 10;
  w += sprintf(w, "%d", static_cast<int>(v));
  if (v < 10 && b % 10)
   w += sprintf(w, ".%02d", b);
  else if (v < 100 && b > 9)
   w += sprintf(w, ".%d", b / 10);
 }
 else
  w += sprintf(w, "%d", static_cast<int>(v));
 const char* a[] = {"", " k", " m", " g", " t", " p", " e", " z", " y"};
 w += sprintf(w, "%s", a[l]);
 if (postfix)
  w += sprintf(w, "%s%s", l ? "" : " ", postfix);
 return d;
}

Question information

Language:
English Edit question
Status:
Answered
For:
libkibi Edit question
Assignee:
No assignee Edit question
Last query:
Last reply:
Revision history for this message
Benjamin Drung (bdrung) said :
#1

Your code is hard to read, because it's not documented and variables with one character are not very descriptive.

Your code works using only integers, but it works only with 1024 as basis. You don't round the values correctly if I read your code correct.

Revision history for this message
Benjamin Drung (bdrung) said :
#2

I took a similar approach than you after stumbling over rounding errors.

Can you help with this problem?

Provide an answer of your own, or ask Olaf van der Spek for more information if necessary.

To post a message you must log in.