The snippet library.
Small, practical examples. Search by task or narrow things down below.
Count newline characters
Count newline bytes in a C file while retaining EOF as an int.
C✓ Tested
Count set bits in an unsigned integer
C: Clearing the lowest set bit on each iteration counts only one iteration per set bit.
C✓ Tested
Count the items in a collection
C: Read the collection’s length instead of hard-coding the loop limit.
C✓ Tested
Create an independent copy of a byte buffer
C: Allocate the exact byte length and copy only after checking the result.
C✓ Tested
Decode a 16-bit big-endian integer
C: Promote bytes to an unsigned integer type before combining shifted values.
C✓ Tested
Decode a validated pair of hexadecimal digits
C: Convert each nibble and reject a nonhexadecimal character before combining them.
C✓ Tested
Divide using a fractional number
C: Use a floating-point operand to preserve the fractional part of a division.
C✓ Tested
Encode a byte buffer as hexadecimal
C: Format each byte as an unsigned two-digit hexadecimal value.
C✓ Tested
Explain a calculation with a comment
C: Keep the code executable while documenting why a fixed input is used.
C✓ Tested
Filter an array in place with a write index
C: Only retained values advance the write position.
C✓ Tested
Find a substring
Use strstr to find a literal substring in a C string.
C✓ Tested
Find an array element
Use a bounded linear search over a C array.
C✓ Tested