
Integer promotions are easy to overlook in embedded C, especially when code moves between MCUs with 16-bit and 32-bit int. Consider this well-defined example:
#include <stdint.h>uint8_t a = 200U;uint8_t b = 100U;uint8_t c = (uint8_t)(a + b); /* c is 44 */
On typical AVR and MSP430 C implementations, a and b promote to 16-bit int; on a typical Cortex-M implementation they promote to 32-bit int. Either way, the intermediate value is 300, and converting it to uint8_t gives 44 modulo 256. The final answer is defined, and the compiler need not actually generate a 16-bit addition on AVR. It can use an 8-bit instruction when the high bits have no observable effect.
The real hazards arise when the promoted type changes a shift’s width, a signed result overflows, a bitwise complement becomes negative, or a signed/unsigned comparison behaves differently on a 16-bit target. This article explains the language rules, distinguishes illustrative assembly from measured target output, and shows portable fixes and a verified real-world libcsp case study.
For ordinary standard integer types, C99/C11/C17 §6.3.1.1 specifies integer promotions: an eligible type with rank no greater than int is converted to int if int can represent every value, or to unsigned int otherwise. The conversion preserves the value, including its sign. C23 retains the essential rule for these types but introduces exceptions for bit-precise integer types (_BitInt) and their bit-fields.
Integer promotions apply where the language specifies them: in the usual arithmetic conversions, to unary +, -, and ~, to both operands of shifts, and as part of default argument promotions. They do not imply every appearance of a small integer is expanded into a multi-byte machine operation.
#include <stdint.h>uint8_t a = 200U;uint8_t b = 100U;uint8_t c = (uint8_t)(a + b);
On a system with 16-bit int:
a converts to signed int with value 200, since all uint8_t values fit.b converts to signed int with value 100.a + b has type int and value 300, safely within range.uint8_t produces 300 % 256 = 44 by the defined unsigned conversion rule.The abstract-machine intermediate type matters for correctness. The compiler may legally use a narrower instruction when it proves the generated code has the same observable result.
The relevant property is the ABI’s int width, not the width of the CPU’s arithmetic logic unit. Common AVR-GCC and MSP430-GCC configurations use 16-bit int, while common ARM Cortex-M configurations use 32-bit int. Other compiler/ABI combinations should be checked rather than inferred from the MCU name.
| Type (typical typedef) | 32-bit int target | 16-bit int target |
|---|---|---|
int8_t, uint8_t | Promote to int | Promote to int |
int16_t (short on 32-bit ABI; int on some 16-bit ABIs) | Promote to int when short | Already int if typedef aliases int; otherwise promotes to int |
uint16_t (unsigned short / unsigned int) | Promote to int | unsigned int (either already that type or promoted from unsigned short) |
int32_t | Usually already int; unchanged | Usually long; unchanged |
uint32_t | Usually already unsigned int; unchanged | Usually unsigned long; unchanged |
The actual underlying typedefs vary by implementation; verify with <stdint.h>, <limits.h>, sizeof, and compiler predefined macros. On a 32-bit-int ABI, uint16_t values through 65535 fit in int, so uint16_t promotes to signed int. On a 16-bit-int ABI, that range cannot fit in int, so the effective type is unsigned int. This distinction is central to the examples below.
For binary arithmetic and comparison operators that use the usual arithmetic conversions, eligible integer operands are promoted and then converted to a common type. In simplified terms, after promotion: operands of the same type stay that type; otherwise greater rank wins among operands of the same signedness. For mixed signedness, the unsigned type wins when its rank is at least the signed type’s rank; otherwise, whether the signed type can represent the unsigned type’s entire range determines the result. Shifts are a special case: the operands are promoted independently, and the result type is that of the promoted left operand.
Consider a typical 16-bit-int system:
#include <stdint.h>uint8_t a = 200U;int16_t b = -50;int result = a + b; /* 150; both operands are int */
Now change the second operand:
uint8_t a = 200U;uint16_t b = 65000U;unsigned int result = a + b; /* 65200 on a 16-bit-int ABI */
Here a becomes signed int while b has the effective type unsigned int; the usual arithmetic conversions make the operation unsigned. If an operand is negative, its conversion to unsigned changes the numerical interpretation modulo UINT_MAX + 1. Avoid reasoning about mixed signedness from the variable names alone.
The shift operators (<<, >>) independently promote their operands. The expression’s type is the promoted left operand, not the assignment destination. A later assignment to uint32_t cannot undo an invalid shift or restore bits already discarded by a 16-bit calculation.
For left shifts, a negative count or a count greater than or equal to the width of the promoted left operand invokes undefined behavior. For a nonnegative signed left operand, C17/C23 additionally require the mathematical product by 2^count to be representable in the result type; otherwise behavior is undefined. Unsigned left shifts operate modulo one more than the maximum value of that unsigned type.
#include <stdint.h>uint16_t high_word = UINT16_C(0x8000);uint32_t bad_address = high_word << 16; /* Undefined on a 16-bit-int ABI */uint32_t good_address = (uint32_t)high_word << 16; /* 0x80000000 */
On a 16-bit-int target, the promoted left operand of high_word << 16 is 16-bit unsigned int. Its shift count equals its width, so the expression has undefined behavior. A particular compiler might warn, emit a zero, or generate some other result; none is guaranteed by C. On a 32-bit-int target, that same uncast expression is also problematic for the value 0x8000: uint16_t promotes to signed int, and 0x8000 << 16 overflows signed 32-bit int.
uint16_t base = UINT16_C(0x0100);uint32_t truncated = base << 8; /* 0 on 16-bit-int targets */uint32_t preserved = (uint32_t)base << 8; /* 0x00010000 */
The base << 8 example is a defined unsigned 16-bit shift on a 16-bit-int target: it wraps modulo 65536 to zero. That is a different failure from a shift count that is out of range. Both are fixed by widening the left operand before the operation.
#include <stdint.h>uint8_t flag = UINT8_C(0x80);uint16_t bad_mask = flag << 8; /* Undefined with 16-bit signed int */
With 16-bit int, flag promotes from uint8_t to signed int (128). The mathematical result of shifting left eight places is 32768, which cannot be represented in signed 16-bit int. The expression has undefined behavior before conversion to uint16_t.
On a 32-bit-int target, the expression ((uint16_t)0x8000) << 16 likewise overflows signed 32-bit int after integer promotion. Casting only the result does not fix it.
uint32_t address = (uint32_t)high_word << 16;uint16_t mask = (uint16_t)((uint32_t)flag << 8);
A cast to uint16_t is sufficient only when the intended left-shift width and value are safe on the particular ABI; uint16_t may itself promote to signed 32-bit int. Casting to uint32_t (or another known sufficiently wide unsigned type) before shifting makes the intent portable between these targets.
#include <stdint.h>uint8_t reg = UINT8_C(0x3C);uint8_t inverted_nibble = (uint8_t)((~reg) >> 4); /* Not portable */
reg promotes to signed int; thus ~reg is the negative value -61 on conventional binary implementations. Right-shifting a negative signed number has implementation-defined behavior in C17/C23. On targets that perform an arithmetic right shift, -61 >> 4 evaluates to -4, and conversion to uint8_t gives 0xFC, not the intended upper nibble 0x0C.
Constrain the byte width before shifting and use an unsigned wide intermediate:
uint8_t inverted = (uint8_t)~reg;uint8_t nibble = (uint8_t)((uint32_t)inverted >> 4); /* 0x0C *//* Or mask the promoted complement before shifting. */uint8_t nibble_masked = (uint8_t)(((uint32_t)(uint8_t)~reg) >> 4);
The cast to uint8_t explicitly implements the desired eight-bit complement. Converting that nonnegative value to uint32_t prevents signed-right-shift ambiguity in the next operation.
A comparison uses the value and effective type of each complete expression, not the storage type you intended for an intermediate. One common error is expecting two uint8_t operands to wrap during addition before a comparison; another is mixing signed literals with uint16_t on a 16-bit-int target. These are well-defined C rules, not compiler defects.
#include <stdint.h>uint8_t a = 200U;uint8_t b = 100U;if (a + b > 250) {/* Executes: the comparison is 300 > 250. */}if ((uint8_t)(a + b) > UINT8_C(250)) {/* Does not execute: explicitly narrowed value is 44. */}
On both 16-bit- and 32-bit-int targets, the operands promote to signed int. a + b is 300, which is representable. Only an explicit conversion to uint8_t before the comparison produces modular arithmetic. The right choice depends on whether the business rule should compare the mathematical sum or the stored byte; narrowing is not automatically the correct fix.
#include <stdint.h>uint16_t reading = UINT16_C(50000);if (reading > -10) {/* True on a 32-bit-int ABI; false on a 16-bit-int ABI. */}
With 32-bit int, reading promotes to signed int, giving 50000 > -10, which is true. With 16-bit int, the effective type of reading is unsigned int, so -10 converts modulo 65536 to 65526U. The comparison 50000U > 65526U is false.
A check for a negative value is generally meaningless for inherently unsigned sensor readings. If you genuinely need a signed comparison, first choose and validate a signed type wide enough to represent the intended range (for example, int32_t on the targets discussed), then explicitly convert both values.
#include <stdint.h>uint8_t status = UINT8_C(0x01);#define STATUS_MASK 0xFEUif (~status == STATUS_MASK) {/* False: ~status is a negative int, not the eight-bit value 0xFE. */}if ((uint8_t)~status == (uint8_t)STATUS_MASK) {/* True: compare the intended eight-bit complement. */}
On typical 16-bit and 32-bit int targets, ~status is -2, rather than an unsigned byte value 254. To operate on a protocol field, explicitly narrow the complement and then compare. Be mindful that the narrowed uint8_t is itself promoted again for the == operation; the promotion is harmless because the intended value has already been selected.
Many 8-bit MCUs use 8-bit data paths and may need multiple instructions for genuinely 16-bit results. But the C promotion rule does not require the compiler to execute every intermediate in 16-bit machine code. Under the as-if rule, a compiler can calculate only the low byte when higher bits cannot affect observable behavior.
The cost depends on whether the entire promoted result is needed, the compiler and optimization flags, register allocation, memory access, and MCU instruction set. Claims of a universal 3x-5x penalty are unsupported. Profile the generated assembly and measure representative workloads on the target.
These two functions have the same defined behavior on standard AVR-GCC targets:
#include <stdint.h>uint8_t a, b, c;void add_native(void){c = (uint8_t)(a + b);}void add_unoptimized(void){c = a + b;}
Both expressions undergo integer promotions. The cast in add_native does not disable promotions, and a correct compiler can optimize both functions to the same instructions. For illustration, a plausible compact AVR sequence is:
; Representative AVR instructions, NOT a captured compiler listinglds r24, a ; 2 cycles: load byte from data memorylds r22, b ; 2 cycles: load byte from data memoryadd r24, r22 ; 1 cycle: low eight bits of sumsts c, r24 ; 2 cycles: store byte in data memory
This illustrative sequence requires 7 cycles for these instructions on a classic ATmega328P (not including call/return), and typically 14 bytes of flash because LDS and STS are two-word instructions. An illustrative sequence that unnecessarily computes the high byte would add CLR, CLR, and ADC instructions; the number of instructions depends on the actual output and is not forced by ISO C.
For a meaningful performance comparison, contrast a function returning uint8_t with one returning the full uint16_t sum of two byte operands. The latter must preserve the carry into bit 8; the former does not. Do not interpret abstract-machine promotions as an automatic instruction-count penalty.
An AVR ATmega328P has an 8x8-bit hardware MUL instruction, while some smaller MCUs lack a hardware multiplier. A full 16-bit product can therefore require more instructions than an 8-bit truncated result. However, optimized code for uint8_t c = (uint8_t)(a * b); needs only the low eight bits, and the compiler may exploit that fact instead of generating a generic 16x16 multiplication routine.
#include <stdint.h>uint8_t multiply_mod256(uint8_t a, uint8_t b){return (uint8_t)(a * b); /* Low eight bits are sufficient. */}uint16_t multiply_full(uint8_t a, uint8_t b){return (uint16_t)(a * b); /* Full product fits 16 bits. */}
For operands up to 255, the full product is at most 65025, so it fits 16-bit unsigned arithmetic; on a 16-bit-int ABI, the expression a * b itself is a signed 16-bit int and can overflow before the conversion. Fix the second function as follows:
uint16_t multiply_full_safe(uint8_t a, uint8_t b){return (uint16_t)((uint32_t)a * (uint32_t)b);}
This deliberately ensures the intermediate multiplication is wide enough and unsigned. It may cost more cycles, but avoids undefined behavior. Any cycle-count comparison must be measured for the chosen compiler and MCU; a specific 15-20-cycle or 80-120-cycle figure is not generally valid.
The sequence below separates the ISO C abstract-machine rules from code generation. Correctness does not depend on whether the target CPU has an 8-bit, 16-bit, or 32-bit ALU.
+----------------------------------------------------------------------+| C SOURCE || uint8_t c = (uint8_t)(a + b); |+----------------------------------------------------------------------+|v+----------------------------------------------------------------------+| ABSTRACT C RULES || Both byte operands promote to int. || a + b has value 300 and type int on common 16/32-bit ABIs. |+----------------------------------------------------------------------+|v+----------------------------------------------------------------------+| CONVERSION TO uint8_t || 300 converted modulo 256 gives 44. |+----------------------------------------------------------------------+|v+----------------------------------------------------------------------+| BACKEND CODE GENERATION || AVR: compiler may emit an 8-bit ADD when high bits are unused. || Cortex-M: compiler may emit an ADD and optional byte truncation. || Actual instructions depend on compiler, ABI and optimization. |+----------------------------------------------------------------------+
The diagram is conceptual, not disassembly. Inspect optimized target output (avr-objdump, arm-none-eabi-objdump, or the relevant toolchain) to determine whether a widening operation was emitted. Also measure optimization settings consistently; -O0, -Os, and -O2 can generate very different instruction sequences without changing the defined result.
Function calls introduce a separate conversion boundary. A properly prototyped function converts each fixed argument to its declared parameter type. Variadic arguments passed through ... instead undergo the default argument promotions: integer promotions for small integer types, and float to double. Format strings must correspond to the actual promoted argument types expected by the conversion specification.
#include <stdint.h>#include <stdio.h>#include <inttypes.h>uint8_t node_id = UINT8_C(0x85);printf("Node ID: 0x%02X\n", (unsigned int)node_id);printf("Node ID (decimal): %" PRIu8 "\n", node_id);
The node_id argument undergoes promotion to int on typical 16-bit- and 32-bit-int systems; for %X, an explicit conversion to unsigned int makes the intended format argument type unambiguous.
A negative signed byte requires particular care:
int8_t err_code = -5;/* Misleading: %X expects unsigned int; negative int is not a byte. *//* printf("Status: 0x%02X\n", err_code); *//* Convert to an 8-bit two's-complement style code, then widen for printf. */printf("Status: 0x%02X\n", (unsigned int)(uint8_t)err_code); /* 0xFB *//* Or print a signed numeric error code. */printf("Status: %d\n", (int)err_code);
The C99 hh length modifier is also available for hhx/hhX, although embedded C libraries sometimes implement reduced printf feature sets. Always verify your embedded logging implementation’s supported formats and enable format-string compiler warnings.
Preventing promotion bugs starts with identifying the intermediate type used by an operator. The following patterns favor explicit unsigned widths for packed data and bit fields while preserving ordinary arithmetic semantics when they are intended. A cast is not automatically beneficial: use it at the place where it changes the operation, rather than merely hiding a narrowing warning after the fact.
#include <stdint.h>uint16_t sample = UINT16_C(0xA5A5);/* Wrong on 16-bit-int targets; signed overflow on 32-bit-int targets. */uint32_t packet_bad = sample << 16;/* The left operand is 32-bit unsigned before shifting. */uint32_t packet_good = (uint32_t)sample << 16;
For assembling a 16-bit field from a high byte, use an unsigned intermediate large enough for the shifted value:
uint8_t byte_val = UINT8_C(0x80);uint16_t word_val = (uint16_t)((uint32_t)byte_val << 8);
The uint32_t cast avoids the 16-bit signed-overflow trap; the final cast expresses that the destination is a 16-bit field. Check dynamic shift counts against the width of the promoted left operand.
When modulo arithmetic is the required protocol operation, make the narrowing explicit:
#include <stdint.h>uint8_t a = 200U;uint8_t b = 100U;uint8_t sum = (uint8_t)(a + b); /* 44 modulo 256 */uint16_t val1 = UINT16_C(65000);uint16_t val2 = UINT16_C(1000);uint16_t total = (uint16_t)((uint32_t)val1 + (uint32_t)val2);
You may use & UINT32_C(0xFF) or & UINT32_C(0xFFFF) to make protocol masks explicit, but the final unsigned conversion already performs the corresponding modulo operation. Masking a result does not repair undefined behavior that happened earlier, such as signed overflow or an invalid shift. Widen operands first when the intermediate result might otherwise overflow.
Unsuffixed decimal integer constants usually have signed int type when their values fit. Unsigned suffixes help document bit masks and unsigned configuration quantities, but do not indiscriminately replace every signed constant: changing signedness can itself change comparison semantics.
#include <stdint.h>#define BUFFER_SIZE 256U#define CRC8_POLYNOMIAL 0x07U#define TIMEOUT_TICKS 1000Uuint16_t reg_val = UINT16_C(100);/* For unsigned values, avoid comparisons against negative constants. */if (reg_val == UINT16_C(0)) {/* Handle zero. */}
For a value that may be negative, use a deliberately signed representation of adequate width; for masks and wire-format fields, use explicitly unsigned types.
#include <stdint.h>uint8_t a = 200U;uint8_t b = 100U;/* Compare mathematical sum: 300 > 250 is true. */if ((uint32_t)a + (uint32_t)b > 250U) {/* Handle a total above 250. */}/* Compare wrapped byte: 44 > 250 is false. */if ((uint8_t)(a + b) > UINT8_C(250)) {/* Intended only if protocol says to wrap first. */}
Choose the domain based on the real requirement. An explicit narrowing cast changes the program’s behavior and is not a universal fix for a compiler warning.
Pack byte fields using a sufficiently wide unsigned operand before each shift:
#include <stdint.h>#define MAKE_UINT16(msb, lsb) \((uint16_t)((((uint32_t)(uint8_t)(msb)) << 8) | \((uint32_t)(uint8_t)(lsb))))#define MAKE_UINT32(b3, b2, b1, b0) \((((uint32_t)(uint8_t)(b3)) << 24) | \(((uint32_t)(uint8_t)(b2)) << 16) | \(((uint32_t)(uint8_t)(b1)) << 8) | \((uint32_t)(uint8_t)(b0)))
The byte casts explicitly constrain each argument to eight bits, and the uint32_t casts make every shift use an unsigned 32-bit left operand. These macros evaluate each argument once, but arguments with side effects should still be avoided in macros. When practical, use static inline functions with uint8_t parameters for better type checking and debugging.
MISRA C:2012’s essential type model helps reviewers detect unintended conversions beyond the ISO C rules. In particular:
For bit assembly, widening before a shift avoids both ISO C problems and the common MISRA 10.8 issue of casting a potentially invalid composite result afterward. MISRA compliance requires checking all applicable rules and any documented deviations; these six examples do not guarantee that every promotion bug is eliminated.
No standard GCC/Clang option disables integer promotions while preserving conforming C semantics. Instead, use compiler warnings, host-side tests, target-width-focused checks, and target disassembly. Diagnostic availability varies by compiler and release; an unsupported warning option must not silently invalidate the build.
The following CMake configuration applies common warnings to a named target, and uses GCC-specific -Warith-conversion only for GCC:
# Replace firmware with your actual executable/library target.target_compile_options(firmware PRIVATE-Wall-Wextra-Wconversion-Wsign-conversion-Wshift-count-overflow)if(CMAKE_C_COMPILER_ID STREQUAL "GNU")target_compile_options(firmware PRIVATE-Warith-conversion-Wshift-overflow=2)endif()
-Warith-conversion is important with GCC: according to its documentation, a warning for arithmetic on a small type that is later converted back to that small type may not be emitted by -Wconversion alone. -Wshift-overflow=2 flags additional signed left-shift cases in GCC modes that support it; verify compiler version and language mode.
#include <stdint.h>uint8_t sum_bytes(uint8_t a, uint8_t b){return a + b; /* GCC -Warith-conversion can diagnose this narrowing. */}
A deliberate conversion may be written return (uint8_t)(a + b); once the intended modulo behavior is confirmed. Static diagnostics are not proofs: compile with a 16-bit-int cross-compiler, run tests for boundary values, and inspect generated code when performance matters.
-mint8 (Use with Caution)AVR-GCC documents -mint8, which assumes an 8-bit int:
# Illustration only: NOT a conforming or generally safe production setting.avr-gcc -mmcu=atmega328p -mint8 -Os main.c -o main.elf
An 8-bit int violates ISO C’s minimum range requirements for int. It also changes integer ABI and library assumptions: conventional AVR Libc and other prebuilt components expect the standard 16-bit-int ABI. Do not use this as a drop-in performance optimisation. Keep the conforming ABI and let the optimizer remove unnecessary high-byte work; profile real code if necessary.
NOINTPROMOTEKeil C51 documents proprietary INTPROMOTE / NOINTPROMOTE directives that can change how integer expressions are evaluated. For illustration, a Keil C51-specific source may contain:
#pragma NOINTPROMOTEunsigned char add_bytes(unsigned char a, unsigned char b){return a + b; /* Keil-specific semantics; not portable ISO C. */}
This pragma is not portable to GCC, Clang, IAR, or other C implementations. Its exact availability and placement should be checked against the particular C51 version and build controls. Prefer explicit types and reviewed conversions in shared or long-lived firmware.
The following snippets show representative instruction patterns that a compiler might select when the return type is uint8_t. They are deliberately not presented as captured avr-gcc, MSP430-GCC, or ARM GCC output: no cross-compiler version, flags, or reproducible build artifacts accompanied the original article. Register selection and exact instruction sequences depend on the ABI and toolchain.
For a reproducible measurement, compile the same function for each target, record compiler versions and flags, and run the target’s disassembler. Compare functionality using boundary-value tests (0, 127, 128, 255) as well as instruction counts.
int)#include <stdint.h>uint8_t process_byte(uint8_t a, uint8_t b){return (uint8_t)(a + b);}
A Cortex-M0+ backend can compute the sum using a native register addition and retain only the low byte. An illustrative Thumb-1-compatible sequence is:
; Representative, not verified compiler disassemblyadds r0, r0, r1 ; add the argumentsuxtb r0, r0 ; retain the low eight bitsbx lr ; return
The exact prologue, registers, and choice of byte-extension instruction may differ. An explicit cast documents the narrowing; it does not prevent C’s required promotions.
int)#include <stdint.h>uint8_t add8_opt(uint8_t a, uint8_t b){return (uint8_t)(a + b);}
The C expression has int type during evaluation, but an optimizing AVR compiler can implement the final modulo-256 result with an 8-bit addition. A representative AVR assembly sequence, not an asserted output from a specific GCC build, is:
; Arguments in common AVR ABI registers; representative onlyadd r24, r22ret
The byte add takes one clock cycle on classic AVR cores; RET has its own cost. The same optimized sequence can be generated when the source omits the explicit cast, because implicit conversion to the return type still discards the high byte. Do not infer a 16-bit instruction penalty from integer promotions alone.
int)#include <stdint.h>uint8_t add_msp(uint8_t a, uint8_t b){return (uint8_t)(a + b);}
The MSP430 instruction set has byte-sized operations. A compiler can use an ADD.B-style instruction when only the low byte of an addition is observed:
; Illustrative only; ABI registers and exact output are toolchain-specificadd.b r13, r12ret
Whether a particular compiler emits this sequence depends on its code generator and calling convention. Evaluate code size and cycles from actual disassembly, especially when inputs are in memory rather than registers.
The CubeSat Space Protocol (libcsp) project merged pull request #976 on 26 August 2026, addressing CSP v2/CFP2 header-packing expressions on targets with 16-bit int. The pull request specifically describes an MSP430FR5964 deployment and fixes shifts by widening operands to uint32_t for CFP2/CAN fields and uint64_t for CSP v2 packed headers.
A representative old expression was:
/* Representative vulnerable CFP2 header-packing expression. */uint32_t id = (packet->id.src & CFP2_SRC_MASK) << CFP2_SRC_OFFSET;
In the libcsp definitions, CFP2_SRC_MASK is 0x3FFF and CFP2_SRC_OFFSET is 18, not 19. The mask and a uint16_t source can leave the left operand effectively 16 bits on an MSP430; shifting it by 18 then invokes undefined behavior. The 32-bit destination does not widen the shift retroactively.
The pull request reports that the physical CFP2 sender field in the CAN identifier remained correct, but the CSP source address in the CFP2 header extension decoded as zero. The reported before/after example was:
Before: cfp_sender=24 src=0 dst=7 sport=15 dport=15After: cfp_sender=24 src=24 dst=7 sport=15 dport=15
The original article’s assertion that the MSP430 hardware definitely reduced the count modulo 16 and placed the source in CAN ID bits [7:3] is not established by the pull request. Undefined shifts do not have a guaranteed machine-level outcome.
The portable correction widens the operand before shifting:
/* Same field layout; operation is now 32-bit unsigned. */uint32_t id = ((uint32_t)(packet->id.src & CFP2_SRC_MASK))<< CFP2_SRC_OFFSET;
The actual patch covers multiple CAN/CSP header fields, not only this expression. This is a verified example of how a cross-target ABI difference can expose an integer-width bug that escaped tests on 32-bit hosts.
Consider reading two bytes of a sensor register over SPI. This is a constructed example, not an attributed failure report from the ADT7410 or LM75 vendor:
#include <stdint.h>uint8_t spi_read_byte(void); /* Hardware-specific implementation. */uint32_t read_sensor_word_bad(void){uint8_t msb = spi_read_byte(); /* Example: 0x85 */uint8_t lsb = spi_read_byte(); /* Example: 0x30 */return (msb << 8) | lsb; /* Undefined on a 16-bit-int target for msb=0x85. */}
On a 16-bit-int ABI, msb promotes to signed int. For msb = 0x85 (133), msb << 8 attempts to compute 34048, which is outside the range of signed 16-bit int. That is undefined behavior. A particular two’s-complement compilation could produce an intermediate negative value that later becomes something like 0xFFFF8530, but the language standard does not guarantee this result, or even guarantee a normal return.
The intended unsigned 16-bit assembly is 0x8530, widened to uint32_t as 0x00008530. Compute it in a wide unsigned type:
uint32_t read_sensor_word(void){uint8_t msb = spi_read_byte();uint8_t lsb = spi_read_byte();return ((uint32_t)msb << 8) | (uint32_t)lsb;}
This expression is portable across the common 16-bit and 32-bit int ABIs. If the hardware register represents a signed temperature, interpret its sign and scale it according to the sensor datasheet after assembling the raw bits; do not rely on accidental signed promotion or implicit sign extension.
Integer promotions are required by ISO C. They become troublesome when developers assume the arithmetic follows a variable’s storage width, or assume every MCU uses 32-bit int. The main hazards are semantic; performance depends on the target compiler’s generated code.
~uint8_t is generally a negative int; narrow it to eight bits before using it as a byte value or shifting it right.int range; a final cast or mask cannot repair undefined behavior.-Wconversion, -Wsign-conversion, GCC’s -Warith-conversion, and boundary tests on the intended 16-bit/32-bit int ABI; treat warnings as aids rather than complete proofs.The libcsp #976 fix demonstrates the concrete payoff: explicitly widening operands before packing fields avoids architecture-dependent corruption while leaving the wire format unchanged. Favor fixed-width unsigned intermediates for wire protocols, explicitly choose where narrowing occurs, and verify any low-level optimization against the generated instructions.
-Wconversion, -Wsign-conversion, -Warith-conversion). GCC Online Documentation#pragma NOINTPROMOTE Directive. Keil Arm Support.Quick Links
Legal Stuff





