fork download
  1. /*
  2. 794 名前:デフォルトの名無しさん[sage] 投稿日:2014/05/26(月) 07:45:41.42 ID:ptXAqcmg [2/4]
  3. お題: ビット演算を四則演算のみで実装せよ。ただし、ループも再帰も使ってはならない。
  4. int など整数が固定長の言語でお願いします。
  5.  
  6. 結構難しいかも。
  7. 上級者の人は、どうやったら計算量を落とせるかも考えてくれるとうれしい。
  8. */
  9. #include <stdio.h>
  10.  
  11. unsigned int not(unsigned int a) {
  12. return -1 - a;
  13. }
  14. unsigned int and(unsigned int a, unsigned int b) {
  15. unsigned int c = 1;
  16. #define ha (a -= (a/c * (b/c + 1) % 2) * c), (c += c)
  17. #define HA ha, ha, ha, ha, ha, ha, ha, ha
  18. return HA, HA, HA, HA, a;
  19. }
  20. unsigned int or(unsigned int a, unsigned int b) {
  21. return not(and(not(a), not(b)));
  22. }
  23. unsigned int xor(unsigned int a, unsigned int b) {
  24. return and(or(a, b), not(and(a, b)));
  25. }
  26.  
  27. int main(void) {
  28. int i, ss[][2] = {{0x1a,0x16},{123456,777},{-1,-1}};
  29. for (i = 0; i < (int)(sizeof(ss)/sizeof(ss[0])); i++) {
  30. int a = ss[i][0], b = ss[i][1];
  31. printf("a=%d b=%d\n", a, b);
  32. printf(" ~a =0x%08X not(a) =0x%08X\n", ~a, not(a));
  33. printf(" a&b=0x%08X and(a,b)=0x%08X\n", a&b, and(a,b));
  34. printf(" a|b=0x%08X or(a,b) =0x%08X\n", a|b, or(a,b));
  35. printf(" a^b=0x%08X or(a,b) =0x%08X\n", a^b, xor(a,b));
  36. }
  37. return 0;
  38. }
  39.  
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
a=26 b=22
  ~a =0xFFFFFFE5 not(a)  =0xFFFFFFE5
  a&b=0x00000012 and(a,b)=0x00000012
  a|b=0x0000001E or(a,b) =0x0000001E
  a^b=0x0000000C or(a,b) =0x0000000C
a=123456 b=777
  ~a =0xFFFE1DBF not(a)  =0xFFFE1DBF
  a&b=0x00000200 and(a,b)=0x00000200
  a|b=0x0001E349 or(a,b) =0x0001E349
  a^b=0x0001E149 or(a,b) =0x0001E149
a=-1 b=-1
  ~a =0x00000000 not(a)  =0x00000000
  a&b=0xFFFFFFFF and(a,b)=0xFFFFFFFF
  a|b=0xFFFFFFFF or(a,b) =0xFFFFFFFF
  a^b=0x00000000 or(a,b) =0x00000000