fork download
  1. #include <stdio.h>
  2. #include <stdint.h>
  3. #include <string.h>
  4.  
  5. void uint16_to_bcd(uint16_t input, uint8_t* bcd) {
  6. uint8_t i, j;
  7. bcd[0] = 0; bcd[1] = 0; bcd[2] = 0;
  8. for (i = 0; i < 16; i++) {
  9. // Коррекция.
  10. for (j = 0; j < 2; j++) {
  11. bcd[j] = ((bcd[j] & 0x0F) >= 0x05) ? (bcd[j] + (uint8_t) 0x03) : bcd[j];
  12. bcd[j] = ((bcd[j] & 0xF0) >= 0x50) ? (bcd[j] + (uint8_t) 0x30) : bcd[j];
  13. }
  14. // Сдвиг.
  15. bcd[2] = (bcd[2] << 1) | (bcd[1] >> 7);
  16. bcd[1] = (bcd[1] << 1) | (bcd[0] >> 7);
  17. bcd[0] = (bcd[0] << 1) | (input >> 15);
  18. input <<= 1;
  19. }
  20. }
  21.  
  22. int test_bcd() {
  23. uint16_t i;
  24. uint8_t bcd[3];
  25. char str1[10];
  26. char str2[10];
  27.  
  28. for (i = 0; i < 0xFFFF; i++) {
  29. uint16_to_bcd(i, bcd);
  30. sprintf(str1, "%02X%02X%02X", bcd[2], bcd[1], bcd[0]);
  31. sprintf(str2, "%06d", i);
  32. if (strcmp(str1, str2))
  33. return -1;
  34. }
  35. return 0;
  36. }
  37.  
  38. int main() {
  39. uint8_t bcd[3];
  40. uint16_to_bcd(12345, bcd);
  41. printf("example 1: %02X %02X %02X\n", bcd[2], bcd[1], bcd[0]);
  42.  
  43. uint16_to_bcd(54679, bcd);
  44. printf("example 2: %02X %02X %02X\n", bcd[2], bcd[1], bcd[0]);
  45.  
  46. if (test_bcd())
  47. printf("BCD test: FAILED");
  48. else
  49. printf("BCD test: OK");
  50. }
  51.  
Success #stdin #stdout 0.02s 9432KB
stdin
Standard input is empty
stdout
example 1: 01 23 45
example 2: 05 46 79
BCD test: OK