PHP - Php Binary And Bitwise
So I have coded php for about 5-6 yrs and have never really needed to use binary conversions and the bitwise operator like >> or << . I took a php class in college but that basically consisted of the students trying to learn php on their own... So i have never had any exposure to that portion of php coding. I have to take an exam on PHP with a bunch of questions that DO NOT show how good of a coder you are. There are a bunch of questions on bitwise operators and binary conversions... Am I missing something??? Whats the point of converting a string to binary or knowing how to do this in your head?
Any help? Similar TutorialsHi all, Is it possible in php to read data from file as binary and operate on it with bitwise operators and save result as binary. Thanks I'm planning on storing RIPEMD-160 passphrase hash's raw binary data in MySQL as BINARY(20). Right now, I'm not sure if one of the following INSERT approach is more preferrable and more efficient: Approach (1) - Using mysqli::real_escape_string() ================================================= Code: [Select] $binhash = $mysqli->real_escape_string(hash('ripemd160', $passphrase, true)); $mysqli->query("INSERT INTO testtbl (Passphrase) VALUES ('" . $binhash . "')"); This approach saves hash() from converting raw binary data to hexadecimal format, but need to process and escape the binary string. Approach (2) - Using UNHEX() on MySQL ===================================== Code: [Select] $hexhash = hash('ripemd160', $passphrase); $mysqli->query("INSERT INTO testtbl (Passphrase) values (UNHEX('" . $hexhash . "'))"); This approach needs hash() to convert binary data to hexadecimal but no need for escaping the string and it put extra load on MySQL to convert the hexadecimal back to binary. I'm at kind of a loss with this. I've read the docs for ~ bitwise NOT, and for ip2long() and I can't see why this is happening. On 2 machines with 32 bit OSs (one PPC Mac, and one Linux box), this does what I'd expect it to do. On an Intel Mac with a 64 bit version of OS X, it does not. echo abs(~ip2long('255.255.255.0')) + 1; I would expect this to return a value of 256. On a PowerMac, dual G5 OS X 10.5.8, (32 bit) and PHP 5.2.11 it returns 256 On a hosting server (unsure what processors) Linux OS (32 bit) and PHP 5.2.14, it returns 256 On an Intel Mac, Core2 Duo, OS X 10.6.8 (64 bit) and PHP 5.2.17, it returns 4294967042 Have I overlooked something in the manual that would explain this, or am I doing something fundamentally wrong with one of the functions? Hi every one, I just want to know what is the use of '<<' and '>>' operators in php hi all, I have an array(1,2,3,4) and i make a form and make checkboxes for this array and user selects 2,3 and 4 when user submit form then i save it in table by making selected check boxes and converting selected values into bitwise equivalent value like this foreach($data['meal_types'] as $v){ $mealTypeBits += pow(2,$v-1); } Now when i have to show user his selected data how will i compare table bitwise saved record with array(1,2,3,4) to get the values that he checked while saving. Here is a simple script which uses bitwise operations to determine whether or not a checkbox has been set. The problem is that if you use the $alpha array, the script doesn't produce the results you should expect. For example, if you set the last checkbox while using the $alpha array, all the checkboxes become set. I partially know why this happens as the PHP-Manual enlightened me: Quote From: http://www.php.net/manual/en/language.operators.bitwise.php Don't right shift for more than 32 bits on 32 bits systems. Don't left shift in case it results to number longer than 32 bits. I attempted to use the GMP_* functions but because those aren't part of the PHP-Standard-Library, I do not wish to rely on them. Is there any way to make these functions work for integers beyond 2^31? Here is a standalone script I'm using to make these tests. $alpha = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'); $delta = range('a', 'z'); function generate($array){ $n = count($array); $c = array(); for($i = 0; $i < $n; ++$i){ $c[bcpow(2, $i)] = $array[$i]; } return $c; } function set($array, $post){ $c = 0; foreach($array as $key => $val) if(isset($post['c'.$key])) $c |= $key; return $c; } function check($num, $category){ if($num & $category) return 'CHECKED'; return ''; } function checkboxes($array, $numval=0){ $i = 0; $form = ''; foreach($array as $key => $val){ $checked = check($numval, $key); $form .= '<input type="checkbox" '.$checked.' name="c'.$key.'" id="c'.$key.'">' . '<label for="c'.$key.'"> '.$val.'</label><br />'; ++$i; } return $form; } $array = generate($alpha); $num = 0; if(isset($_POST['action'])){ $num = set($array, $_POST); echo $num; } echo '<form action="y.php" method="post" style="width: 400px; border: 1px solid black;">'; echo checkboxes($array, $num); echo '<input type="submit" name="action" value="Set" />'; echo '</form>'; I am just messing around, but I can't figure this out... $hx = bin2hex('a'); echo base_convert($hx, 16, 2); prints out 1100001 but I really want it to print: 01100001 why is the first 0 missing when my code runs? Hi I need to convert hex or Decimal to Binary but can't find any function. Any one have one or ideas please. :confused:can any one please guide me through this. i want to calculate binary income like FOR 1 ST PAIR 1:2 OR 2:1 1ST PAIR 1:2 OR 2:1 1:1 UNLIMITED DEPTH WEEKLY CAPPING 30 PAIR i have created a binary tree and i am also able to display it. but don't know how to make pairs and implement that,and provide an income. i really need this and it is urgent, any help will be of great value for me, this is for my college project, actually i am a not so good at algorithms. thanks. [attachment deleted by admin] hi all. I am working on a MLM project in which i have more than 30,000 members followed by the root member,i have to store member automatically in binary tree form like 1 is root 2 is child of 1 3 is child of 1 Then 4 is child of 2 5 is child of 2 and so on ...... i have to design database for that. please help ive been doing some research on this, and i cant seem to find an answer that makes sense. im reading the manual on mysql_real_escape() and I know how to use the function, but in the description: Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used. What is an example of inserting "binary data" as described above?? As far as I understand that would be any numerical values and a string would not apply.. But does not seem to add up. A binary file cannot be inserted, so Im a bit lost. Any thoughts welcome. I am running Apache with the PHP module installed on Debian Linux. My goal is to launch a binary in a background process and then feed it commands via fifo. The binary I need to launch has a config file which lives in the home directory of the apache user (in my case the user name apache is started with is www-data). www-data's home dir was the web root so I changed it to /home/www-data. I also change the shell from /bin/sh to /bin/bash for www-data. Neither of these changes are present when I load a php file from a browser. This script: Code: [Select] <?php echo "User: " . exec('whoami') . "<br>"; echo "Shell: " . exec('ps -p $$ | grep sh') . "<br>"; ?> Outputs this: Code: [Select] User: www-data Shell: 9179 ? 00:00:00 sh Also if I execute the binary it does seem to read the config file which is in the www-data users directory. I have set the home dir and the web root to be owned by www-data and it's read and writeable. How do I get php to execute the binary so it has access to the users home directory and uses the bash shell? Are there any other ways to launch and control a binary on a unix system via php? Hey guys, i am a college student and working on a project of mlm ad want to display the binary income tree,and also calculate the income that is given to each node. Please see the attachments for the binary tree structure and database table structure. Thanks. [attachment deleted by admin] This is my first try to display binary tree so please go easy on me. I am trying to display binary tree using array. The values are stored in mysql. Structure of mysql- Code: [Select] CREATE TABLE IF NOT EXISTS `tree` ( `parent` int(7) NOT NULL, `rchild` int(7) NOT NULL, `lchild` int(7) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; Display should look like Code: [Select] 1 ______|______ | | 2 3 ______|______ | | 4 5 My Code till now- Code: [Select] <?php include 'connection.php'; $rsearch = "SELECT rchild FROM tree WHERE parent='".$parent."'"; $lsearch = "SELECT lchild FROM tree WHERE parent='".$parent."'"; $rexec = mysql_query($rsearch); $lexec = mysql_query($lsearch); while($rrow = mysql_fetch_assoc($rexec)) // Putting right branch in an array first { $rtree[$i][0] = $rrow['parent'] ; $rtree[$i][1] = $rrow['lchild'] ; $rtree[$i][2] = $rrow['rchild'] ; $i++; } while($lrow = mysql_fetch_assoc($lexec)) // Putting left branch in an array { $ltree[$j][0] = $lrow['parent'] ; $ltree[$j][1] = $lrow['lchild'] ; $ltree[$j][2] = $lrow['rchild'] ; $j++; } function displaytree($parent,$array) { // Im stuck here. Can someone please help me with it } ?> I am stuck at displaying the tree function. Can someone please point me in the right direction ? I am trying to count left node of a binary tree.I made a function but my result is always 3 . Code:- Code: [Select] <?php include'config.php'; // Connect database function leftcount($node) //Function to calculate leftcount { $sql = "SELECT lchild,rchild FROM tree WHERE parent = '$node'"; $execsql = mysql_query($sql); $array = mysql_fetch_array($execsql); if(!empty($array['lchild'])) { $count++; leftcount($array['lchild']); } if(!empty($array['rchild'])) { $count++; leftcount($array['rchild']); } $totalcount = 1 + $count; return $totalcount; } $parent = "2"; $left = leftcount($parent); echo $left; ?> Can someone please point the error in my logic ? I searched google but i only got scripts with classes and i don't want to use classes. I am trying to display binary tree level wise. Breadth-first tree traversal can be used in it.Can anyone point me towards its logic or point me towards a good tutorial. Hi, guys. I'm trying to wrap my head around trying to read a header in a binary file in php. So, far, I have been able to get the data into a string using file_get_contents. Now, I think I need to use unpack, but it's a bit confusing to me still. For example, my file starts by having a 1 byte version number, 4 bytes to represent a number of walls, then "number of walls" * 40 bytes for the actual walls. But, the problem is, the wall itself is a structure composed of various elements to make up that 40 bytes, from which I'll need to pick out a specific area of interest. I can do this easily in C, but in php. I can't think how to grab the info. Any ideas? Maybe just how to read 1 byte, 4 bytes, then "number of walls" * 40 bytes will get me in the right direction. Is this the correct way to write binary data to a file? $string = 'this is a string'; $handle = fopen('b.dat', 'wb'); for($i=0;$i<strlen($string);$i++){ $hx = bin2hex($string{$i}); fwrite($handle, pack("H*", $hx)); } If so, how do I read it an convert it back to a string? If it is not correct, how do I do it? I have a column in my db called 'Sold' which is set to Binary. I need a dropdown in my form, that converst the binary into 'True', 'False' for the options, and also selects the one that is set in the db. This is for an edit form, so will then need to adapt it for a add form. This is my code, which doesnt seem to be working <?php $id = $_GET["id"]; $sqlSold = "SELECT Sold FROM Products WHERE idProducts = $id;"; $products = [ 'True' => true, 'False' => false ]; ?> <select name="Sold"> <option selected="selected">Choose one</option> <?php foreach($products as $item){ echo "<option value='strtolower($item)'>$item</option>"; } ?> </select>
I was looking at the manual:
http://php.net/manua...ction.fopen.php
And I noticed the the binary mode 'b' is missing from the list. Any reason why?
|