swindonshaun Posted August 31, 2009 Share Posted August 31, 2009 Hello there folks, This is my first time posting to such a forum, so please be gentle with me! What I am trying to do is write a script which represents the days of the week as binary (7 bits, each representing one day). I can do this fine. My problem comes when I want to apply the ~ (bitwise NOT operator). It turns it into a 32 bit number, but it gets the desired result at the end of the number e.g. In: 1100000 Out: 11111111111111111111111110011110 I have been looking high and low to see if I am doing something wrong. I have cast the variables as (int). I think I understand why it behaves like this, and thought I had come up with a solution, which involving ANDing the output to 0000..1111 (25 zeroes and 7 ones), but the result is always 0. What am I doing wrong? Is there some way of declaring a number as binary as you would with hexadecimal? Many thanks and apologies if this is a dumb question. Shaun Link to comment https://forums.phpfreaks.com/topic/172589-binary-calculations/ Share on other sites More sharing options...
Daniel0 Posted August 31, 2009 Share Posted August 31, 2009 It turns it into a 32 bit number It already was. Is there some way of declaring a number as binary as you would with hexadecimal? No, but you can just write it in base 8, base 10 or base 16, which PHP has a syntax for. Internally in memory any number is stored as binary regardless, so the base n expansion you use when displaying it is irrelevant. Link to comment https://forums.phpfreaks.com/topic/172589-binary-calculations/#findComment-909800 Share on other sites More sharing options...
corbin Posted August 31, 2009 Share Posted August 31, 2009 If this were a lower level language, you could use a byte (8 bits) instead of an int (32 bits).... But anyway, you could always use either & or << to break it back down to 7 bits (padded with zeros). Link to comment https://forums.phpfreaks.com/topic/172589-binary-calculations/#findComment-909908 Share on other sites More sharing options...
roopurt18 Posted August 31, 2009 Share Posted August 31, 2009 And it with 0x000000ff Link to comment https://forums.phpfreaks.com/topic/172589-binary-calculations/#findComment-909925 Share on other sites More sharing options...
ignace Posted September 1, 2009 Share Posted September 1, 2009 And it with 0x000000ff By that he means: $number & 0x000000FF Just in case you wouldn't know what he means with "and it" Link to comment https://forums.phpfreaks.com/topic/172589-binary-calculations/#findComment-910318 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.