Module operator with unsigned characters

Trying to get some kind of code to work, and the module doesnโ€™t want to do what I want to do it ... which means I'm wrong.

I have an unsigned char that I am trying to separate hours / minutes / seconds so that I can display them on screen in Ascii.

The variable secs is unsigned int . Everything else is an unsigned char . I want to get results in an unsigned char so as not to waste memory. Work in the embedded environment.

Does anyone want to look at a code snippet and tell me what I did wrong?

 hours = secs/3600.0; minutes =(secs/60.0)-(hours*3600); seconds =secs-(hours*3600)-(minutes*60); sec_ones =(unsigned char)((seconds%10)); sec_tens =(unsigned char)((seconds-sec_ones)%100); min_ones =(unsigned char)(minutes%10); min_tens =(unsigned char)((minutes-min_ones)%100); hrs_ones =(unsigned char)(hours%10); hrs_tens =(unsigned char)((hours-hrs_ones)%100); 
+2
source share
4 answers
 minutes =(secs/60.0)-(hours*3600); 

it should be

 minutes =(secs/60.0)-(hours*60); 

In addition, it works for fairly small input: http://ideone.com/VPKP1

There are some things that I would change. For example, it makes no sense to do double division, and then assign the result back to unsigned char , you can just do integer division.

+2
source

You mentioned that it is an embedded program.

 seconds = secs-(hours*3600)-(minutes*60); 

hours is an unsigned char pushed to int in the hours*3600 expression.

If you are working with a 16-bit int , you will have problems with the line above. On two systems with a 16-bit complement, the int range changes from -32768 to 32767 , which means that you have overflow when hours have >= 10 .

+1
source

you first do the calculations with double , since you use double constants.

then module calculations will not be performed as unsigned char , because it is a narrow type. usually it is first raised to int , and then the calculations will be performed.

Usually, you are better off using unsigned int directly for all of your variables. Char types are only useful when you want to save space.

0
source

your program is simply spelled incorrectly, try to do it, it works correctly

 unsigned int secs = 5000; unsigned char sec_ones,sec_tens,min_ones,min_tens,hrs_ones,hrs_tens, hours, minutes, seconds; hours = secs/3600.0; minutes =(secs/60.0)-(hours*60); seconds =secs-(hours*3600)-(minutes*60); sec_ones =(unsigned char)((seconds%10)); sec_tens =(unsigned char)(seconds/10); min_ones =(unsigned char)(minutes%10); min_tens =(unsigned char)(minutes/10); hrs_ones =(unsigned char)(hours%10); hrs_tens =(unsigned char)(hours/100); printf("%.1u%.1u:%.1u%.1u:%.1u%.1u\n",hrs_tens,hrs_ones,min_tens,min_ones,sec_tens,sec_ones ); 
0
source

Source: https://habr.com/ru/post/958080/


All Articles