Skip to content

Floating variables missing? #1

@HLeithner

Description

@HLeithner

Hi,

I think this is a feature request, I would need to convert bytes to double and float. I would like to use this lib for interaction knx bus system.

My initial attempt is the following code for 2 bytes signed float, it borrowed from the calimero java code https://github.com/calimero-project/calimero-core/blob/master/src/tuwien/auto/calimero/dptxlator/DPTXlator2ByteFloat.java

function decode2ByteFloat($byte1, $byte2) {
	$i = 0;
	//$data = pack( "i", 0x0c6a);
	$data = [ $byte1, $byte2 ];
	// DPT bits high byte: MEEEEMMM, low byte: MMMMMMMM
	// left align all mantissa bits
	$v = (($data[$i] & 0x80) << 24) | (($data[$i] & 0x7) << 28) | ($data[$i + 1] << 20);

	// normalize
	$v >>= 20;
	$exp = ($data[$i] & 0x78) >> 3;
	$value = (1 << $exp) * $v * 0.01;

	return $value;
}

function encode2ByteFloat($value) {
	$dst = array();
// encoding: value = (0.01*M)*2^E
	$v = $value * 100.0;
		$e = 0;
		for (; $v < -2048.0; $v /= 2)
			$e++;
		for (; $v > 2047.0; $v /= 2)
			$e++;
		$m = (int) round($v) & 0x7FF;
		$msb = (float) ($e << 3 | $m >> 8);
		if ($value < 0.0)
			$msb |= 0x80;
		$dst[0] = $msb;
		$dst[1] = ord(pack('c', $m));
		return $dst;
}

Would be great if you can support floating variables too.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions