Is there any reason why arithmetic operation on shorts and bytes return int?

js.mdnq js_adddot+mdng at gmail.com
Wed Dec 12 01:57:24 PST 2012


On Wednesday, 12 December 2012 at 08:23:48 UTC, Simen Kjaeraas 
wrote:
> On 2012-09-12 00:12, js.mdnq <js_adddot+mdng at gmail.com> wrote:
>
>> struct bbyte {
>> byte value;
>> ...
>> }
>>
>> bbyte a; bbyte b;
>>
>> b = a + b; // uses bbyte's operators and casts to do the 
>> computation and assignment but then returns a bbyte instead of 
>> an int.
>>
>> You should have no problems implicitly converting bbyte to 
>> built in types or built in types to bbyte.
>
> Not entirely true. Converting from bbyte to built-in works, but 
> these
> are to my knowledge currently impossible:
>
> void foo(bbyte b);
> byte b;
>
> foo(b); // No conversion.
>
>
> bbyte bar( ) {
>     byte b;
>     return b;
> }


What I mean is that you use bbyte for all your arithmetic 
operations and computations.  When you need to convert it to a 
byte(hopefully at the end of the process), you can use an 
implicit cast.


struct bbyte {
	byte b;
	byte opCast(bbyte a) { return a.b; }
	alias b this;


	bbyte bar(byte b) { bbyte q; q.b = b; return q; }

	byte foo(bbyte b) {  return b.b; }
}

byte bar2(byte b) { return b; }



int main(string[] argv)
{

	bbyte bb;
	byte b;

	bb.foo(bb); 		
	bb.bar(b);
	b = bb;
	bb = b;
}

the point is no explicit op casts are required. Essentially a 
bbyte is a byte. One can overload all the operators that are 
needed for bit manipulation, even using asm if necessary and one 
should be able to hide most of the details. `alias this` might 
not stop some of the value propagation in some cases. If one only 
converts to the built-in types when actually needed(when passing 
to and from routines that use them) but uses bbyte for all bit 
manipulations it shouldn't be much of a problem(if at all).


The idea is that conversion from bbyte to byte does not induce an 
expansion to int, only the arithmetic operations. Hence, 
overriding them can stop that.

but something like

byte b1;
byte b2;
bbyte b3 = b1 + b2;

is computing the arithmetic operation from byte(which converts to 
an int). This is why I say one must use bbytes for all arithmetic 
operations to solve that problem. (or write a cast for int, if 
you just don't want to deal with it but don't mind the expansion)

But this works:

byte b1;
byte b2;
bbyte b3;
b3 = b1 + b2;

if one has bbyte opAssign(int i) { this.b = cast(byte)i; return 
this; } in bbyte.

which avoids having to do b3 = cast(byte)(b1 + b2) which I think 
was what the original post was about.


More information about the Digitalmars-d mailing list