Michael Heidelberg - 6 months ago 21

C Question

I've already read some Q&A concerning questions similar to mine, but I am still not sure if my case is the same as those questions.

I am wondering why we need two casts here:

`(ULONG)(USHORT)(carry >> BITPERDGT)`

`*sptr_l++ = (USHORT)(carry = (ULONG)*aptr_l++`

+ (ULONG)*bptr_l++ + (ULONG)(USHORT)(carry >> BITPERDGT));

ULONG :

`typedef unsigned long ULONG;`

USHORT:

`typedef unsigned short USHORT;`

C library used: FLINT

Book: Cryptogtaphy in C and C++

Answer

Trying to take OP's code piece by piece.

```
*sptr_l++ = (USHORT)(carry = (ULONG)*aptr_l++
+ (ULONG)*bptr_l++ + (ULONG)(USHORT)(carry >> BITPERDGT));
```

This is somewhat simplified to

```
carry = (ULONG)*aptr_l++ + (ULONG)*bptr_l++ + (ULONG)(USHORT)(carry >> BITPERDGT);
*sptr_l++ = (USHORT)carry;
```

Given the range of `ULONG`

>= range of `USHORT`

and likely is *greater than* ...

`(USHORT)(carry >> BITPERDGT)`

simple shifts the value of `carry`

the least `BITPERDGT`

significant bits out. The remaining are cast with `(USHORT)`

result in the most significant bits being zeroed.

Then code casts *unnecessarily* to `ULONG`

with `(ULONG)(USHORT)(carry >> BITPERDGT));`

. It is not needed as the subsequent addition with a `ULONG`

will cause `(USHORT)(carry >> BITPERDGT`

to be promoted to `ULONG`

even without the cast.

Why casting twice in this line?

Although not *needed*, the `(ULONG)`

cast may exist to emphasize to programmers that the result of `(USHORT)(carry >> BITPERDGT))`

is promoted before the addition.