help cast
bauss
jj_1337 at live.dk
Mon Mar 19 11:52:42 UTC 2018
On Monday, 19 March 2018 at 11:20:05 UTC, Steven Schveighoffer
wrote:
> On 3/18/18 4:07 PM, Jonathan M Davis wrote:
>
>> That's exactly what it's doing, and when you have multiple
>> elements in the
>> literal, it quickly gets a lot more pleasant than casting each
>> element
>> individually. e.g.
>>
>> cast(ubyte[])[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>
>> vs
>>
>> [cast(ubyte)0, cast(ubyte)1, cast(ubyte)2, cast(ubyte)3,
>> cast(ubyte)4,
>> cast(ubyte)5, cast(ubyte)6, cast(ubyte)7, cast(ubyte)8,
>> cast(ubyte)9,
>> cast(ubyte)10]
>>
>> I use this trick all the time when creating arrays of integral
>> types smaller
>> than int, precisely because casting each element is a royal
>> pain and way
>> harder to read.
>
> Let me adjust your example a bit, and see if you still agree:
>
> auto bytes = cast(ubyte[])[55_444, 289, 1_000_000, 846,
> 123_456_789];
>
> writeln(bytes); // [148, 33, 64, 78, 21]
>
> I have used cast(ubyte[]) to get ubytes as well, but I normally
> would do this for values that actually *could be* ubytes. for
> values higher than ubytes, I would not have expected implicit
> truncation. It's especially confusing to someone who has seen
> when you cast an int[] to a ubyte[], and gets the bytes for
> that same data. When I use cast(ubyte[]), I took it to mean
> "pretend this is a ubyte[] literal", not "cast each element to
> ubyte".
>
> I can also see this biting someone who has a long set of
> ubytes, and accidentally does one that is larger than 255.
>
> -Steve
An even funnier example.
auto bytes = cast(ubyte[])cast(int[])[55_444, 289, 1_000_000,
846, 123_456_789];
auto bytes2 = cast(int[])[55_444, 289, 1_000_000, 846,
123_456_789];
auto bytes3 = cast(ubyte[])bytes2;
writeln(bytes); // Guess what the output is here.
writeln(bytes2); // Prints:[55444, 289, 1000000, 846,
123456789]
writeln(bytes3); // Prints: [148, 216, 0, 0, 33, 1, 0, 0, 64,
66, 15, 0, 78, 3, 0, 0, 21, 205, 91, 7]
More information about the Digitalmars-d
mailing list