BCD.h 2.0 KB

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