fork(1) download
  1. #include <stdio.h>
  2.  
  3.  
  4. #define applyMask(mask, bit) do { \
  5. if(tmp & mask) { \
  6. tmp &= mask; \
  7. shift |= bit; \
  8. } \
  9. else { \
  10. tmp &= ~mask; \
  11. } \
  12. } while (0);
  13.  
  14. // convert 12bit to 8
  15. unsigned char encode(unsigned short sample)
  16. {
  17. unsigned short tmp;
  18. unsigned char out, shift = 0;
  19.  
  20.  
  21. sample -= 0x800; // убираем начальное смещение
  22.  
  23. out = (sample & 0x800) >> 4; // получаем знак числа
  24.  
  25. // инвертируем если необходимо
  26. if(out) {
  27. sample = ~sample;
  28. }
  29.  
  30.  
  31. // Ищем старший установленный бит
  32. // (можно заменить на более оптимальную встроенную инструкцию)
  33. tmp = sample >> 4;
  34. applyMask(0x78, 4);
  35. applyMask(0x66, 2);
  36. applyMask(0x55, 1);
  37.  
  38. // Добавляем экспоненту
  39. out |= shift << 4;
  40.  
  41. // Добавляем мантиссу
  42. out |= (sample >> (shift ? --shift : 0)) & 0xF;
  43.  
  44. return out;
  45.  
  46. }
  47.  
  48. unsigned short decode(unsigned char sample)
  49. {
  50. unsigned short out, shift;
  51.  
  52. shift = (sample >> 4) & 7;
  53. out = (sample & 0xF) | (shift ? --shift, 0x10 : 0);
  54. out <<= shift;
  55.  
  56. if(shift) {
  57. out |= out >> 5;
  58. }
  59.  
  60.  
  61. if(sample & 0x80) {
  62. out = ~out;
  63. }
  64.  
  65. return out + 0x800;
  66. }
  67.  
  68. int main(void) {
  69.  
  70. unsigned short a[] = {0, 0x40, 0xFF0, 0xFFF, 0x81F, 0x82D, 0x59f, 0x7CF, 0x200, 0x936, 0x7ff};
  71. unsigned char encoded;
  72.  
  73. int i = 0;
  74.  
  75. for(i=0; i < (sizeof(a)/sizeof(a[0])); i++) {
  76.  
  77. encoded = encode(a[i]);
  78.  
  79. printf("\noriginal = 0x%X"
  80. "\nencoded = 0x%X"
  81. "\ndecoded = 0x%X\n", a[i], encoded, decode(encoded));
  82.  
  83. }
  84.  
  85.  
  86.  
  87.  
  88.  
  89. // your code goes here
  90. return 0;
  91. }
  92.  
Success #stdin #stdout 0s 2248KB
stdin
Standard input is empty
stdout
original = 0x0
encoded = 0xFF
decoded = 0x1

original = 0x40
encoded = 0xFE
decoded = 0x43

original = 0xFF0
encoded = 0x7F
decoded = 0xFFE

original = 0xFFF
encoded = 0x7F
decoded = 0xFFE

original = 0x81F
encoded = 0x1F
decoded = 0x81F

original = 0x82D
encoded = 0x26
decoded = 0x82D

original = 0x59F
encoded = 0xE3
decoded = 0x58C

original = 0x7CF
encoded = 0xA8
decoded = 0x7CE

original = 0x200
encoded = 0xF7
decoded = 0x211

original = 0x936
encoded = 0x53
decoded = 0x939

original = 0x7FF
encoded = 0x80
decoded = 0x7FF