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