Thread overview | |||||||
---|---|---|---|---|---|---|---|
|
July 18, 2017 How do I cast to from byte[] <-> double for making a small assembler language VM to work? | ||||
---|---|---|---|---|
| ||||
class OpCode { private: byte[] bytes_; public: void opCall(Program program) const; byte[] bytes() const { return bytes_.dup; } } class AddD : OpCode { private: uint d, s; public: this(uint dst, uint src) { d = dst; s = src; } override void opCall(Program p) const { p[d..d+8] = cast(byte[])(cast(double)p[d..d+8] + cast(double)p[s..s+8]); } } --- The cast at the bottom gives a compiler error (can't cast byte[] to double). |
July 18, 2017 Re: How do I cast to from byte[] <-> double for making a small assembler language VM to work? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Enjoys Math | On Tuesday, 18 July 2017 at 11:06:22 UTC, Enjoys Math wrote:
> class OpCode
> {
> private:
> byte[] bytes_;
>
> public:
> void opCall(Program program) const;
>
> byte[] bytes() const {
> return bytes_.dup;
> }
> }
>
>
>
> class AddD : OpCode
> {
> private:
> uint d, s;
>
> public:
> this(uint dst, uint src) {
> d = dst;
> s = src;
> }
>
> override void opCall(Program p) const
> {
> p[d..d+8] = cast(byte[])(cast(double)p[d..d+8] + cast(double)p[s..s+8]);
> }
> }
>
>
> ---
>
> The cast at the bottom gives a compiler error (can't cast byte[] to double)
Byte[] is a slice
what you want is *(cast(double*)p + d) = *(cast(double*)p + d) + *(cast(double*)p + s)
|
July 18, 2017 Re: How do I cast to from byte[] <-> double for making a small assembler language VM to work? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Enjoys Math | On Tuesday, 18 July 2017 at 11:06:22 UTC, Enjoys Math wrote: > [ ... ] > The cast at the bottom gives a compiler error (can't cast byte[] to double). If you want to see how it's done check: https://github.com/UplinkCoder/dmd/blob/newCTFE_on_master/src/ddmd/ctfe/bc.d Though if you have the choice I'd recommend proper 3-address opcodes. |
July 18, 2017 Re: How do I cast to from byte[] <-> double for making a small assembler language VM to work? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Enjoys Math | Maybe use a union?
union U {
double d;
byte[double.sizeof] bytes;
}
U u;
u.bytes = ...;
double d = u.d;
... // do something with d
// or:
U u;
u.d = 3.14159;
byte[] b = u.bytes[];
... // do something with b
Casting a pointer may run into alignment issues, if your byte[] isn't aligned to a double.
T
--
Only boring people get bored. -- JM
|
July 18, 2017 Re: How do I cast to from byte[] <-> double for making a small assembler language VM to work? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Stefan Koch | Thanks for the replies. I will look at 3-address opcodes and consider unions. *Wonders if it matters that Program is a struct with opSlice / opSliceAssign overloaded*. |
Copyright © 1999-2021 by the D Language Foundation