According to this answer the EVM by default uses two's complement notation for handling signed integers. However for my application I would like to work with the sign-magnitude representation
where the sign can either be 0 or 1 corresponding to + or - respectively and the remaining bits comprise the magnitude. For example, if a int8 variable has a value of +1 it would be represented in binary as 0000_0001 and if it has a value of -1 it would 1000_0001 in sign-magnitude notation.
However since the EVM uses two's complement I first have to convert it into sign-magnitude representation before I can work with it. How exactly would I do this in a gas-efficient manner?
function twos_comp_to_sign_mag(int8) returns(int8);
// 255 in binary is 1111_1111 or -1 in two's complement notation
// 129 in binary is 1000_0001 or -1 in sign-magnitude notation
twos_comp_to_sign_mag(255) == 129
&is a bitwise AND, you can read up on it, but in essence it compares each bit in the value to the corresponding bit in the mask and if both are 1 then the value at that bit in the result is 1 else it's 0 – MShakeG Sep 25 '23 at 07:26