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 Quote 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. Quote 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? Quote 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 Quote Link to comment https://forums.phpfreaks.com/topic/185674-basic-bitwise-operation/#findComment-990042 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.