View previous topic :: View next topic |
Author |
Message |
DarkKobold
Joined: 21 Jan 2004 Posts: 4
|
8 bit unsigned vs signed |
Posted: Wed Jan 21, 2004 9:56 pm |
|
|
Hi all.
I believe that by using the char identifier, I can use it as an unsigned 8 bit integer. (I may be wrong). I am trying to use it for time, a total of 3 minutes, which is 180 seconds. (obviously) However, if I use an algorithm to decode the individual numbers, such as
min = 0;
tensec = 0;
//get x
if ((x - 60) > 0)
{
x -= 60;
min++;
}
if ((x - 10) > 0)
{
tensec++;
}
sec = x;
will the negation require it to convert to 16 bit math, therefore requiring more overhead? |
|
|
dvsoft
Joined: 28 Nov 2003 Posts: 46
|
|
Posted: Thu Jan 22, 2004 2:04 am |
|
|
Bonjour
int8 Value,Minute,Seconde;
Value = getc();
Minute = Value / 60;
Seconde = Value % 60;
Bonne journée |
|
|
Mark
Joined: 07 Sep 2003 Posts: 2838 Location: Atlanta, GA
|
|
Posted: Thu Jan 22, 2004 7:06 am |
|
|
There is a little problem with your routine. You should use a loop:
Code: |
min = 0;
tensec = 0;
//get x
while (x >= 60)
{
x -= 60;
min++;
}
while (x >= 10)
{
x -= 10;
tensec++;
}
sec = x;
|
|
|
|
Neutone
Joined: 08 Sep 2003 Posts: 839 Location: Houston
|
Re: 8 bit unsigned vs signed |
Posted: Thu Jan 22, 2004 8:17 am |
|
|
DarkKobold wrote: |
if ((x - 60) > 0)
|
This line can be a problem.
A better way to construct the syntax would be this.
This avoids having an under flow without having to use signed math. The compiler will actually break the C statement into assembly, performs a subtraction and then test for an underflow to solve the IF. Subtracting 1 from 0 will result in 255 and an underflow when using an unsigned 8 bit integer. The test you wrote will only work for signed numbers. |
|
|
DarkKobold
Joined: 21 Jan 2004 Posts: 4
|
|
Posted: Thu Jan 22, 2004 3:30 pm |
|
|
Thank you for all of your help - I am still a tad confused. Will this guarentee to stay an 8 bit number? can you have an 8 bit number ranged 255-0 in PICC? |
|
|
Mark
Joined: 07 Sep 2003 Posts: 2838 Location: Atlanta, GA
|
|
Posted: Thu Jan 22, 2004 3:46 pm |
|
|
x-60 will always be greater than 0 unless x=60. The reason for this is since there is no sign bit, numbers cannot be < 0 only >= 0. If x=0 and you subtract 1 from it, x will now equal 255. Hope this clears it up for you. |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Thu Jan 22, 2004 3:48 pm |
|
|
Quote: | Will this guarantee to stay an 8 bit number? |
The compiler will not change the data type. It will stay as
an unsigned char (ie., 8 bits, unsigned). The assembly
code generated by the compiler will be for 8-bit unsigned math.
Quote: | Can you have an 8 bit number ranged 255-0 in PICC? |
Yes. Just use "char" as the data type.
In CCS, a "char" is the same an "unsigned char". |
|
|
|