Improved code for encoding INT64_MIN
diff --git a/src/qcbor_encode.c b/src/qcbor_encode.c
index 26d86ce..53df657 100644
--- a/src/qcbor_encode.c
+++ b/src/qcbor_encode.c
@@ -658,8 +658,13 @@
uint64_t uValue;
if(nNum < 0) {
- /* In CBOR -1 encodes as 0x00 with major type negative int. */
- uValue = (uint64_t)(-nNum - 1);
+ /* In CBOR -1 encodes as 0x00 with major type negative int.
+ * First add one as a signed integer because that will not
+ * overflow. Then change the sign as needed for encoding. (The
+ * opposite order, changing the sign and subtracting, can cause
+ * an overflow when encoding INT64_MIN. */
+ int64_t nTmp = nNum + 1;
+ uValue = (uint64_t)-nTmp;
uMajorType = CBOR_MAJOR_TYPE_NEGATIVE_INT;
} else {
uValue = (uint64_t)nNum;