What the heck am i doing wrong? I'm just trying to create a 8 bit unsigned variable.
H. S. Teoh
hsteoh at qfbox.info
Wed May 21 19:43:42 UTC 2025
On Wed, May 21, 2025 at 05:47:20PM +0000, WhatMeWorry via Digitalmars-d-learn wrote:
> On Friday, 16 May 2025 at 19:04:24 UTC, WhatMeWorry wrote:
> > /+ SDL3 has a function
> > bool SDL_SetTextureAlphaMod(SDL_Texture *texture, Uint8 alpha);
> > which has a Uint8 for one of its parameters. So I try to use a
> > ubyte
> > +/
> >
> > [...]
>
> So what would be best practice here?
I think Walter's suggestion is to use int for computations, and narrow
ints like ubyte only for storage. So inside your function you'd be
loading values into ints and doing computations as ints, and when
storing back to whatever structure you'd do a range check and then cast
the value. So something like this:
```
int tmp = myData.shortValue;
tmp = ... // computation here
myData.shortValue = tmp.to!ubyte; // std.conv.to does range checks
// or you can do it yourself
```
> Declare an int, manually make sure the value stays between 0 and 255,
> and then cast it to the ubyte?
Pretty much what std.conv.to does. You could just do something like:
```
myData.shortValue = (myData.shortValue * whatever + something).to!ubyte;
```
That's assuming you want regular semantics with narrow int arithmetic.
My nopromote module/hack is intended for doing narrow int arithmetic
without checks, i.e., when either you're 100% sure wraparound isn't a
problem and you want to skip the range checks, or when you *want*
wraparound semantics (like using ubyte/ushort wraparound to implement a
ring buffer).
T
--
Time flies like an arrow. Fruit flies like a banana.
More information about the Digitalmars-d-learn
mailing list