SchweppesAle Posted December 19, 2009 Share Posted December 19, 2009 $x = 0; echo ~$x; // will output -1 was wondering how this works since the only bit you need to represent 0 is 0 Link to comment https://forums.phpfreaks.com/topic/185674-basic-bitwise-operation/ Share on other sites More sharing options...
genericnumber1 Posted December 19, 2009 Share Posted December 19, 2009 ~ reverses all bits. So 0 in 8 bits is... 00000000 (binary) or 0x00 (hex) and ~0 is the reverse of that, which is... 11111111 (binary) or 0xff (hex) this number, 0xff, is -1 in binary. To find out why negative numbers are represented in this way (why is -1 0xff and not 10000001//0x81?) you can read up on two's complement. The main reason for this binary representation comes down to making it much easier to represent negative numbers at a lower level. Eg, subtraction is simply addition of a negative number, addition of negative numbers can be done without special cases in the same circuitry as addition of positive numbers, etc. Link to comment https://forums.phpfreaks.com/topic/185674-basic-bitwise-operation/#findComment-980481 Share on other sites More sharing options...
SchweppesAle Posted January 7, 2010 Author Share Posted January 7, 2010 ~ reverses all bits. So 0 in 8 bits is... 00000000 (binary) or 0x00 (hex) and ~0 is the reverse of that, which is... 11111111 (binary) or 0xff (hex) this number, 0xff, is -1 in binary. To find out why negative numbers are represented in this way (why is -1 0xff and not 10000001//0x81?) you can read up on two's complement. The main reason for this binary representation comes down to making it much easier to represent negative numbers at a lower level. Eg, subtraction is simply addition of a negative number, addition of negative numbers can be done without special cases in the same circuitry as addition of positive numbers, etc. so with two's complimentary, I would calculate the numerical value of a binary string the normal way unless the most significant(left most?) bit is equal to 1. Is that correct? Link to comment https://forums.phpfreaks.com/topic/185674-basic-bitwise-operation/#findComment-990041 Share on other sites More sharing options...
SchweppesAle Posted January 7, 2010 Author Share Posted January 7, 2010 nevermind -> http://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html completely forgot about how to do this Link to comment https://forums.phpfreaks.com/topic/185674-basic-bitwise-operation/#findComment-990042 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.