Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.76 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4.  
  5. int replicateSign(int x) {
  6.     int sign=x>>31;
  7.    
  8.     // replicate the bit into the entire int
  9.     int tmp = sign|(sign<<1);       // 2lsb
  10.     tmp = tmp|(tmp<<2);             // 4lsb
  11.     tmp = tmp|(tmp<<4);             // 8lsb
  12.     tmp = tmp|(tmp<<8);             // 16lsb
  13.     tmp = tmp|(tmp<<16);            // 32lsb
  14.     return tmp;
  15. }
  16. int abs1(int x) {
  17.     int signMask=replicateSign(x);
  18.     int negX=-x;
  19.    
  20.     // apply masks; if sign bit is 1 (meaning negative), we want -x,
  21.     // and if it is 0 we want x
  22.     return (signMask&negX) | ((~signMask)&x);
  23. }
  24. int max(int a,int b) {
  25.     return (a+b+abs1(a-b))/2;
  26. }
  27. int main(int argc, char** argv) {
  28.     if(argc<3) {
  29.         fprintf(stderr,"usage: %s a b\n",argv[0]);
  30.         return 1;
  31.     }
  32.    
  33.     printf("%d\n", max(atoi(argv[1]), atoi(argv[2])));
  34.     return 0;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement