Jump to content

How do I emulate a c union?


carlwenrich

Recommended Posts

You didn't say "convert to PHP" in your first post. ;)  Can I see the C code?  There's no such thing as a union in PHP because it's loosely typed, so the type of the variable doesn't matter, and it'll occupy the same location in memory even if you change types. >_>

Sorry, I thought it would be obvious that I'm converting to php, since this is a php forum... my bad.

Here's the code I need to convert:

 

typedef struct {

 

char from;

 

char to;

 

char promote;

 

char bits;

 

} move_bytes;

 

 

 

typedef union {

 

move_bytes b;

 

int u;

 

} move;

 

 

Okay.  I tried to write up a basic union class, and it seems to work for me.  For the types though, you need to use the type that gettype() returns, and not the actual type.  Ex: int would really be integer in the class constructor.  Here:

 

<?php
class union {
protected $data;
protected $types;

public function __construct(array $types) {
	$this->types = $types;
}

public function access($name)
{
	if ($this->data['name'] == $name) {
		return $this->data['value'];
	}
	else {
		return null;
	}
}

public function set($name, $val)
{
	$type = $this->_type($val);
	if (in_array($name, array_keys($this->types)) && ($this->types[$name] == $type || (gettype($var) == 'object' && $var instanceof $this->types[$name]))) {
		$this->data['name'] = $name;
		$this->data['value'] = $val;
		$this->data['type'] = $type;
		return true;		
	}
	else {
		return false;
	}
}

private function _type($var)
{
	$type = gettype($var);
	if ($type == 'object') {
		$type = get_class($var);
	}
	return $type;
}

}

class foo{public function __toString() { return "Foo!"; }}
class bar{ }

$u = new union(array('test' => 'foo'));
if ($u->set('test', new foo())) {
echo $u->access('test');
}
else {
echo "Failed";
}
echo "\n";
?>

 

Try it. >_<

have a look at these

 

www.php.net/pack

www.php.net/unpack

 

<?php
$i = pack('c*', 0x41,0x42,0x43,0x44);

echo '<br>';

$a = unpack('c*', "$i");                            // unpack as char

echo '<pre>', print_r($a, true), '</pre>';

$b = unpack('N', $i);                               // unpack as int

echo '<pre>', print_r($b, true), '</pre>';
?>

-->
Array
(
    [1] => 65
    [2] => 66
    [3] => 67
    [4] => 68
)

Array
(
    [1] => 1094861636
)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.