llvm.org GIT mirror
Implement a getBitsNeeded method to determine how many bits are needed to represent a string in binary form by an APInt. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@35968 91177308-0d34-0410-b5e6-96231b3b80d8 Reid Spencer 13 years ago
2 changed file(s) with 43 addition(s) and 0 deletion(s).
 839 839 assert(getActiveBits() <= 64 && "Too many bits for int64_t"); 840 840 return int64_t(pVal[0]); 841 841 } 842 843 /// This method determines how many bits are required to hold the APInt 844 /// equivalent of the string given by \p str of length \p slen. 845 /// @brief Get bits required for string value. 846 static uint32_t getBitsNeeded(const char* str, uint32_t slen, uint8_t radix); 847 842 848 /// countLeadingZeros - This function is an APInt version of the 843 849 /// countLeadingZeros_{32,64} functions in MathExtras.h. It counts the number 844 850 /// of zeros from the most significant bit to the first one bit.
 656 656 if ((*this)[bitPosition]) clear(bitPosition); 657 657 else set(bitPosition); 658 658 return *this; 659 } 660 661 uint32_t APInt::getBitsNeeded(const char* str, uint32_t slen, uint8_t radix) { 662 assert(str != 0 && "Invalid value string"); 663 assert(slen > 0 && "Invalid string length"); 664 665 // Each computation below needs to know if its negative 666 uint32_t isNegative = str[0] == '-'; 667 if (isNegative) { 668 slen--; 669 str++; 670 } 671 // For radixes of power-of-two values, the bits required is accurately and 672 // easily computed 673 if (radix == 2) 674 return slen + isNegative; 675 if (radix == 8) 676 return slen * 3 + isNegative; 677 if (radix == 16) 678 return slen * 4 + isNegative; 679 680 // Otherwise it must be radix == 10, the hard case 681 assert(radix == 10 && "Invalid radix"); 682 683 // This is grossly inefficient but accurate. We could probably do something 684 // with a computation of roughly slen*64/20 and then adjust by the value of 685 // the first few digits. But, I'm not sure how accurate that could be. 686 687 // Compute a sufficient number of bits that is always large enough but might 688 // be too large. This avoids the assertion in the constructor. 689 uint32_t sufficient = slen*64/18; 690 691 // Convert to the actual binary value. 692 APInt tmp(sufficient, str, slen, radix); 693 694 // Compute how many bits are required. 695 return isNegative + tmp.logBase2(); 659 696 } 660 697 661 698 uint64_t APInt::getHashValue() const {