Results 1 to 3 of 3
Long story short, my issue is that I'm having a hard time trying to get the number of digits in a uint64_t variable. The reason I'm using this is I ...
- 07-08-2011 #1Just Joined!
- Join Date
- Nov 2010
- Posts
- 6
Getting number of digits in uint64_t
Long story short, my issue is that I'm having a hard time trying to get the number of digits in a uint64_t variable. The reason I'm using this is I want to make sure I get x amount of digits inside of a variable before I use it, but since the higher the digits, the better the program is.
I currently use the following code, and it works, but my loop will never exit because the length is always 0:
Here's my code with the loop (that calls numdigits()):Code:/** * numbdigits() * number: The number to evaluate [in] * * Returns the number of digits found in a number. **/ uint64_t numdigits(uint64_t number){ uint64_t tmp = number; uint64_t i = 0; if(number < 0) tmp = -tmp; while(tmp){ tmp /= 10; i++; } return i; }
Anyone know what's going on? :/ getrand() returns a uint64_t as well (and works). The only way the while() loop ends without my intervention is if I do curd += numdigits(val) instead...but, that gives a false value as well.Code:uint64_t sized_num(int digits){ uint64_t val = 2; uint64_t tmp = 0; uint64_t curd = 0; // Current digits while(curd <= digits){ tmp = getrand(1, 2, 3, 4, 5, 6); val = tmp * tmp; curd = numdigits(val); } return val; }
- 07-10-2011 #2Linux Guru
- Join Date
- Apr 2009
- Location
- I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
- Posts
- 8,974
First, a uint64_t is unsigned. Your test for number < 0 is meaningless. Myself, I would consider printing the number to a string and then seeing what the length is. IE:
I have oversized the buffer length just to be "safe". You can reduce the size according to the maximum number of digits you can find in a 64-bit unsigned integer. Since sprintf() returns the number of digits printed, there you have the answer with a minimum of fuss.Code:char buffer[256]; return sprintf(buffer, "%llu", number);
Sometimes, real fast is almost as good as real time.
Just remember, Semper Gumbi - always be flexible!
- 07-11-2011 #3
I generally tend to printf stuff in a standard format (especially in a loop, and then end the program so I can look at the output). It gives you more of an idea to how the data flows. Another option could be to use gdb. Just debug the thing, with a good debugger (such as gdb) or the poor mans debugger (printf(%X, val)


Reply With Quote