Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
Can I make a calculation with a value outside of the range of my variable?

I'm coding in C and I know the values that can be stored in a uint8_t range from 0 to 255. I want to store a value that is the percentage of MAX_INTENSITY, declared as: #define MAX_INTENSITY 200

Can I do the following: uint8_t my_intensity = (MAX_INTENSITY * percentage) / 100; ?

The result will be 200 or less, but during the calculation, the intermediate result can be superior to 255, e.g. with percentage = 50, MAX_INTENSITY * percentage = 10'000. Can this cause a problem, even if the final result will be 100, o in the range of a uint8_t?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

In C, the rules to determine the type used for each intermediary computation are somewhat intricate, but for your particular case quite easy:

The multiplication MAX_INTENSITY * percentage involves an integer constant 200 of type int and a variable percentage. If the type of percentage is int or a smaller type such as uint8_t, this operand will undergo an integer promotion to type int and the result will have type int, then used as an operand for the division by 100, another integer constant with type int, hence a computation with type int and a result of the same type. The result will be converted to the type of the destination, uint8_t, which is performed by take the positive modulo 256, a fully defined operation, especially if percentage is known to be in range 0 to 200.

Therefore, your definition is correct:

uint8_t my_intensity = (MAX_INTENSITY * percentage) / 100;

You might nevertheless consider using type int for this local variable, as there is no benefit in typing it with a smaller type in this context.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!