-3

Is there a way to get the number of element in a long long in c++? for example I want to count the number of element in 0x993232BF, the answer should be 8. Thanks in advance.

  • 1
    Those are called elements and not bytes or digits? – ifconfig Sep 14 '17 at 01:20
  • `std::cout << sizeof (long long);` – Fureeish Sep 14 '17 at 01:22
  • Possible duplicate of [What does the C++ standard state the size of int, long type to be?](https://stackoverflow.com/questions/589575/what-does-the-c-standard-state-the-size-of-int-long-type-to-be) –  Sep 14 '17 at 01:27
  • 2
    Do you mean the number of _bytes_ or _nibbles_ ("hex digits")? Also, are you looking for nibbles needed to represent a _value_, or the _capacity_ of a long long? (Also, FYI, `0x993232BF` is an int; `0x993232BFLL` would be a long long; `0x993232BFULL` an unsigned long long if you care). – H Walters Sep 14 '17 at 01:28
  • 2
    `long long` is 64bits on many systems. `0x993232BF` is just a hex string. The numeric value it represents takes up a minimum of 4 bytes, but it could go up to 8 bytes, eg `0x993232BFFFFFFFFF`. What are you REALLY looking for? – Remy Lebeau Sep 14 '17 at 01:30
  • 1
    What "elements" are you talking about? What's an "element"? – AnT stands with Russia Sep 14 '17 at 01:30

2 Answers2

1
int count_nibbles(long long n)
{
    int r=0;
    while(n > 0)
    {
        n >>= 4;
        r++;
    }
    return r;
}

or if you prefer as suggested in the comments:

int count_nibbles(long long n)
{
   for(; n > 0; n >>= 4) r++;
   return r;
}
norlesh
  • 1,749
  • 11
  • 23
  • Beware that the result of right shifting of negative values is implementation-defined. I would suggest the argument be `unsigned long long` instead. (You can also use logarithms to find the answer without a loop.) – cdhowie Sep 14 '17 at 02:12
1

If your goal is to find the minimum number of hex digits ("nibbles") required to represent the number, you can find that by using logarithms base 16. More generally, you can find the number of digits required for any base:

template <std::size_t base>
int count_digits(unsigned long long v) {
    return std::ceil(std::log(static_cast<double>(v) + 1) / std::log(base));
}
cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • This uses floating point, so introduces imprecision and rounding errors that may affect the result. – Peter Sep 14 '17 at 06:40
  • Precision is not required at the scale we are talking about here. We only care about the order of magnitude of the number, which floating point can represent quite well. E.g. in the number 0xA12345678, we only really care about 0xAXXXXXXXX. – cdhowie Sep 14 '17 at 15:01