How to convert from ubyte[] to and from float?

uri via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Oct 19 22:59:50 PDT 2014


On Sunday, 19 October 2014 at 03:14:26 UTC, Charles Hixson via 
Digitalmars-d-learn wrote:
> What is the best way to convert from a part of a ubyte[] to a 
> float?
>
> I've tried converting the ubyte[] into a uint, but neither 
> casting the uint to a float nor to!float work.
>
> I suppose I could use a "trick record" union, but that seems 
> inelegant.  If I use pointers, the alignment may 
> (unpredictably) not be proper (whatever that means these days).

Is this what you're after?
http://dlang.org/phobos/std_bitmanip.html#.peek
http://dlang.org/phobos/std_bitmanip.html#.read
http://dlang.org/phobos/std_bitmanip.html#.write

These accept indices, or you can just slice the ubyte[] to the 
part you need.

---

import std.stdio;
import std.bitmanip;
import std.system;
void main()
{
     // UBYTE[] to FLOAT
     //
     // 6.5535000E+004           00-FF-7F-47
     ubyte[] ubval = [0, 0xff, 0x7f, 0x47];
     auto fval = ubval.peek!(float, Endian.littleEndian);
     writefln("%s as float: %s", ubval, fval);
     writefln("%s as float: %s", ubval, ubval.read!(float, 
Endian.littleEndian));

     // 16383.8                  00-FF-7F-46
     ubval = [0, 0xff, 0x7f, 0x46];
     fval = ubval.peek!(float, Endian.littleEndian);
     writefln("%s as float: %s", ubval, fval);
     writefln("%s as float: %s", ubval, ubval.read!(float, 
Endian.littleEndian));

     // FLOAT to UBYTE[]
     ubval = [0, 0, 0, 0];
     std.bitmanip.write!(float, Endian.littleEndian)(ubval, 
65535.0f, 0);
     writefln("%s as ubyte[]: %s", fval, ubval);
     ubval = [0, 0, 0, 0];
     std.bitmanip.write!(float, Endian.littleEndian)(ubval, fval, 
0);
     writefln("%s as ubyte[]: %s", fval, ubval);


}

---


More information about the Digitalmars-d-learn mailing list