Search code examples
arduino

Use case of "-" in front of variable "Sum" and how it converts and into what?


I am referring to the below code for my use case, but I cannot understand the use case of "-" in front of a variable "sum". I have tried googling references or documentation for the same but couldn't find it. Can anyone explain what it does and why it is used? If you have any documentation please do share.

void setup()
    {
        Serial.begin(9600);
    }

byte pack[5] = {0x00, 0x10, 0x00, 0x86, 0x6A};
int pack_size = 5;

void loop()
{
    byte sum = 0;
    for (int i = 0; i < pack_size-1; i++) {
        sum += pack[i];
    }
    Serial.print("Sum of received data bytes                       = ");
    printhexbyte(sum);

    byte calculated_cksum = -sum;
    Serial.print("Calculated checksum                              = ");
    printhexbyte(calculated_cksum);
    
    byte crcbyte = pack[pack_size-1];
    Serial.print("Received checksum byte                           = ");
    printhexbyte(crcbyte);
    
    byte overall = sum+crcbyte;
    Serial.print("Sum of received data bytes and received checksum = ");
    printhexbyte(overall);
    Serial.println();
    
    delay(1000);
}

void printhexbyte(byte x)
{
    Serial.print("0x");
    if (x < 16) {
        Serial.print('0');
    }
    Serial.print(x, HEX);
    Serial.println();
}

Output:- 
    [color=#0000ff]Sum of received data bytes                       = 0x96
    Calculated checksum                              = 0x6A
    Received checksum byte                           = 0x6A
    Sum of received data bytes and received checksum = 0x00[/color]

Solution

  • In computer, a negative number is often stored as the two's complement form, 0x96 is 0b10010110 in binary, the negative of 0x96 in two's compliment form is one's compliment of 0x96 plus 1

    0b10010110    // 0x96
    0b01101001    // one's compliment of 0x96, i.e. revised every bit
           + 1    // add one to give the two's compliment value
    0b01101010    // two's compliment of 0x96 = 0x6A