fork download
  1. #include <stdint.h>
  2. #include "stdio.h"
  3.  
  4. typedef uint16_t uint16;
  5.  
  6. #define DEPTH 4
  7.  
  8. void print16( char* text, uint16 *a)
  9. {
  10. // int i=0;
  11.  
  12. printf("%s 0x",text);
  13. for ( int i=DEPTH; i; i--)
  14. printf("%02x",a[i-1]);
  15. printf("\n");
  16. }
  17.  
  18.  
  19.  
  20.  
  21.  
  22. void sum1(uint16 *a, uint16 *b, uint16 *sum)
  23. {
  24. sum[0]=0;
  25.  
  26. for (int i=0; i < DEPTH; i++)
  27. {
  28. if ( a[i] > 256 && b[i] > 256)
  29. printf("Error!");
  30. sum[i] = (a[i] + b[i]+sum[i]) & 0xff;
  31. if (i < DEPTH-1) sum[i+1] = (a[i] + b[i]) >> 8;
  32. }
  33. }
  34.  
  35.  
  36. void mul2(uint16 *a, uint16 b, uint16 *res)
  37. {
  38. uint16 tmp;
  39. res[0]=0;
  40.  
  41. for (int i=0; i < DEPTH; i++)
  42. {
  43. tmp = (res[i] + b*a[i]);
  44. res[i] = tmp & 0xff;
  45. res[i+1] = tmp >> 8;
  46. }
  47. }
  48.  
  49. void shl (uint16 *a, uint16 bytes)
  50. {
  51. for (int i=DEPTH-1; i > bytes-1; i--)
  52. a[i] = a[i-bytes];
  53. for (int i=bytes-1; i >=0; i--)
  54. a[i] = 0;
  55.  
  56. }
  57.  
  58.  
  59. void copy(uint16 *a, uint16 *b)
  60. {
  61. for (int i = 0; i < DEPTH; i++)
  62. b[i] = a[i];
  63. }
  64.  
  65.  
  66. void mul1(uint16 *a, uint16 *b, uint16 *mul)
  67. {
  68.  
  69. uint16 tmp[DEPTH];
  70. uint16 res[DEPTH];
  71.  
  72.  
  73. for (int i=0; i < DEPTH ; i++)
  74. {
  75. mul2(a,b[i],tmp);
  76. shl(tmp,i);
  77. sum1(tmp,mul,res);
  78. copy(res,mul);
  79. }
  80.  
  81. }
  82.  
  83.  
  84.  
  85. int main() {
  86.  
  87. uint16 b[] = { 0x78, 0x56, 0x34, 0x12 }; // 65535
  88. uint16 a[] = { 0xee, 0xaa, 0x11, 0x44 }; // 39321
  89.  
  90. uint16 mulres[] = {
  91. 0x0,0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
  92.  
  93. mul1(a,b,mulres);
  94. print16("a = ", a);
  95. print16("b = ", b);
  96. print16("a*b = ",mulres);
  97. return 0;
  98. }
Success #stdin #stdout 0s 4452KB
stdin
Standard input is empty
stdout
a  =   0x4411aaee
b  =   0x12345678
a*b =  0x4c0c1390