Post Reply 
Twos Complement
02-18-2023, 07:24 PM (This post was last modified: 02-20-2023 05:48 PM by gehakte_bits.)
Post: #4
RE: Twos Complement
This might help, it follows mostly the traditional 2sC methods around..
(added save Signed state for those that use Signed, and crop to the requested bit width.)
Code:

// 2023.0218 pretty-prime v0.3b
#pragma mode(separator(.,;) integer(h32))

// cmpl_2(#FBh,8) -> -5
// cmpl_2(#FFFBh,8) -> -5
// cmpl_2(#FBh,16) -> 251
// cmpl_2(-5,16) -> #FFFBh
// cmpl_2(5,16) -> #5h

//===============
// 2's Complement
//===============
EXPORT cmpl_2(x,m)
BEGIN
LOCAL s:=Signed;
  Signed:=0; 
  CASE 

    IF TYPE(x)=0 THEN                       // real to integer
      x:=IP(x);
      IF -2^(m-1)≤x<2^(m-1) THEN            // range check integer m sized
        x:=SETBITS(R→B(x,m));
      ELSE 
        x:=0;
      END;
    END;

    IF TYPE(x)=1 THEN                       // integer to real
      IF BITAND(x,2^(m-1)) THEN             // test msb bit neg flag
        x:=-1*(1+BITNOT(SETBITS(x,m-1)));   // (invert m-bits)+1 to real
      ELSE 
         x:=B→R(SETBITS(x,m));
      END;
    END;

  END;
  Signed:=s;
  RETURN x;
END;
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
Twos Complement - akmarul - 02-14-2023, 10:09 PM
RE: Twos Complement - EdS2 - 02-15-2023, 07:58 AM
RE: Twos Complement - Joe Horn - 02-15-2023, 08:36 AM
RE: Twos Complement - gehakte_bits - 02-18-2023 07:24 PM
RE: Twos Complement - phucshuhari - 04-04-2024, 07:39 AM
RE: Twos Complement - BruceH - 04-04-2024, 02:30 PM



User(s) browsing this thread: 1 Guest(s)