BCD.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //===- llvm/Support/BCD.h - Binary-Coded Decimal utility functions -*- C++ -*-//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file declares some utility functions for encoding/decoding BCD values.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_SUPPORT_BCD_H
  13. #define LLVM_SUPPORT_BCD_H
  14. #include <assert.h>
  15. #include <cstddef>
  16. #include <cstdint>
  17. namespace llvm {
  18. // Decode a packed BCD value.
  19. // Maximum value of int64_t is 9,223,372,036,854,775,807. These are 18 usable
  20. // decimal digits. Thus BCD numbers of up to 9 bytes can be converted.
  21. // Please note that s390 supports BCD numbers up to a length of 16 bytes.
  22. inline int64_t decodePackedBCD(const uint8_t *Ptr, size_t ByteLen,
  23. bool IsSigned = true) {
  24. assert(ByteLen >= 1 && ByteLen <= 9 && "Invalid BCD number");
  25. int64_t Value = 0;
  26. size_t RunLen = ByteLen - static_cast<unsigned>(IsSigned);
  27. for (size_t I = 0; I < RunLen; ++I) {
  28. uint8_t DecodedByteValue = ((Ptr[I] >> 4) & 0x0f) * 10 + (Ptr[I] & 0x0f);
  29. Value = (Value * 100) + DecodedByteValue;
  30. }
  31. if (IsSigned) {
  32. uint8_t DecodedByteValue = (Ptr[ByteLen - 1] >> 4) & 0x0f;
  33. uint8_t Sign = Ptr[ByteLen - 1] & 0x0f;
  34. Value = (Value * 10) + DecodedByteValue;
  35. if (Sign == 0x0d || Sign == 0x0b)
  36. Value *= -1;
  37. }
  38. return Value;
  39. }
  40. template <typename ResultT, typename ValT>
  41. inline ResultT decodePackedBCD(const ValT Val, bool IsSigned = true) {
  42. return static_cast<ResultT>(decodePackedBCD(
  43. reinterpret_cast<const uint8_t *>(&Val), sizeof(ValT), IsSigned));
  44. }
  45. } // namespace llvm
  46. #endif // LLVM_SUPPORT_BCD_H