Performing signed arithmetic on unsigned variable without storing value in another signed variable

Hi,

I am trying to see if it is possible to perform signed arithmetic on a short unsigned variable. Is this possible or do I have to store the unsigned value in a signed variable to perform signed arithmetic on the data ? Thanks in advance.
Last edited on
Integer arithmetic operators do not operate on types smaller than int
The unsigned short value would be subject to integral promotion

On architectures in use today, (signed) int would be able to hold the entire range of values that unsigned short can hold; and the unsigned short value would be implicitly converted to a (signed) int.
Hi JLBorges,

Thanks for your reply. Unfortunately, it has to be using short type since the result of the calculation must be stored back into an unsigned short variable. I can't use int or other data types for the variable holding the final result.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <climits>

int main()
{
    static_assert( USHRT_MAX <= INT_MAX, "unsigned short is promoted to (signed) int" ) ;

    unsigned short us = 2 ;
    signed short ss = -3 ;

    us = us * ss ;
    // a. convert us to int: get int(2)
    // b. convert ss to int: get int(-3)
    // c. multiply int(2) and int(-3): get int(-6)
    // d. convert int(-6) to unsigned short and store result in us

    std::cout << us << '\n' // typically 65530
              << (unsigned short)int(-6) << '\n' ; // typically 65530
}

http://coliru.stacked-crooked.com/a/9136068709b8d08d
Topic archived. No new replies allowed.