简体   繁体   中英

Increment char array in C

I got an char array like this:

uchar myBytes[4] = { 0x01, 0x23, 0x45, 0xFF };

What is the easiest/best way to increment the last element, propagating the carry to earlier elements? My result should be

0x01, 0x23, 0x46, 0x00

You can increment the bytes starting by the end of the array and compare the new value with the old one. If it is lesser, that mean that the conversion of the (integer) sum, has been folded over UCHAR_MAX.

Here is a possible code:

#include <stdio.h>

int main()
{
    unsigned char myBytes[4] = { 0x01, 0x23, 0x45, 0xFF };
    for (int i = 3; i >= 0; i--) {
        // mBytes[i] is promoted to int and the sum is converted to unsigned char
        unsigned char newer = 1 + myBytes[i];
        if (myBytes[i] < newer) break;         // stop at first non overflow
        myBytes[i] = newer;
    }
    for (int i = 0; i < 4; i++) {
        printf("0x%02x ", myBytes[i]);
    }
    printf("\n");
    return 0;
}

It gives as expected:

0x01 0x23 0x46 0x00

References from draft n1570 at 6.3.1.3 Signed and unsigned integers [conversions] (emphasize mine)

1 When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type .

for (int i = 3; i >= 0; i--) if (++myBytes[i]) break;

这是我能想到的最简单的解决方案。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM