NanoPB: How to handle enums in C

See also: C++ version: How to handle enums in C++

NanoPB is a code-size optimized Protocol Buffers implementation for embedded systems. This post shows how to handle enum types in C with NanoPB.

Proto definition

First, create a .proto file with enums:

enums.proto
syntax = "proto3";

package example;

enum Status {
  UNKNOWN = 0;
  OK = 1;
  ERROR = 2;
  BUSY = 3;
}

message EnumMessage {
  Status status = 1;
}

Generate NanoPB code

Generate the NanoPB code:

example.sh
protoc --nanopb_out=. enums.proto

This will generate enums.pb.h and enums.pb.c.

C example

Here’s a complete C example handling enums:

enums_example.c
#include <stdio.h>
#include <stdint.h>
#include "enums.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"

// Helper function to convert enum to string
const char* status_to_string(example_Status status) {
    switch (status) {
        case example_Status_UNKNOWN: return "UNKNOWN";
        case example_Status_OK: return "OK";
        case example_Status_ERROR: return "ERROR";
        case example_Status_BUSY: return "BUSY";
        default: return "INVALID";
    }
}

int main() {
    // Buffer for encoded message
    uint8_t buffer[64];
    size_t message_length;
    
    // --- ENCODING ---
    example_EnumMessage message = example_EnumMessage_init_zero;
    
    // Set enum value
    message.status = example_Status_OK;
    
    // Create stream for encoding
    pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
    
    // Encode the message
    if (!pb_encode(&ostream, example_EnumMessage_fields, &message)) {
        printf("Encoding failed: %s\n", PB_GET_ERROR(&ostream));
        return 1;
    }
    
    message_length = ostream.bytes_written;
    printf("Encoded %zu bytes\n", message_length);
    
    // Print hex dump of encoded data
    printf("Encoded data: ");
    for (size_t i = 0; i < message_length; i++) {
        printf("%02x ", buffer[i]);
    }
    printf("\n");
    
    // --- DECODING ---
    example_EnumMessage decoded = example_EnumMessage_init_zero;
    
    // Create stream for decoding
    pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
    
    // Decode the message
    if (!pb_decode(&istream, example_EnumMessage_fields, &decoded)) {
        printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
        return 1;
    }
    
    // Print decoded value
    printf("Decoded value:\n");
    printf("  status: %s (enum value: %d)\n", 
           status_to_string(decoded.status), (int)decoded.status);
    
    return 0;
}

Compile command

Compile the example with nanopb. NanoPB is typically used by including the source files directly in your project:

example.sh
gcc -o enums_example enums_example.c enums.pb.c pb_common.c pb_encode.c pb_decode.c -I.

Note: NanoPB source files (pb_common.c, pb_encode.c, pb_decode.c) need to be compiled directly with your project. You can obtain these from the NanoPB GitHub repository.

Python test script

To verify the encoding, you can use Python’s protobuf library:

test_enums.py
import enums_pb2

# Read the binary data
with open('encoded.bin', 'rb') as f:
    data = f.read()

# Decode
msg = enums_pb2.EnumMessage()
msg.ParseFromString(data)

print("Python decoded values:")
print(f"  status: {enums_pb2.Status.Name(msg.status)}")

First, compile the Python protobuf definitions:

example.sh
protoc --python_out=. enums.proto

Then modify the C example to save the encoded data to a file:

example.c
// After encoding, add this:
FILE *f = fopen("encoded.bin", "wb");
fwrite(buffer, 1, message_length, f);
fclose(f);

Example with enum in switch statement

Here’s an example showing how to use enums in switch statements:

enums_switch_example.c
#include <stdio.h>
#include <stdint.h>
#include "enums.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"

void handle_status(example_Status status) {
    printf("Handling status: ");
    
    switch (status) {
        case example_Status_UNKNOWN:
            printf("UNKNOWN - Default state\n");
            break;
        case example_Status_OK:
            printf("OK - Operation successful\n");
            break;
        case example_Status_ERROR:
            printf("ERROR - Operation failed\n");
            break;
        case example_Status_BUSY:
            printf("BUSY - System busy\n");
            break;
        default:
            printf("INVALID - Unknown enum value\n");
            break;
    }
}

int main() {
    uint8_t buffer[64];
    size_t message_length;
    
    // Test all enum values
    example_Status test_values[] = {
        example_Status_UNKNOWN,
        example_Status_OK,
        example_Status_ERROR,
        example_Status_BUSY
    };
    
    for (size_t i = 0; i < 4; i++) {
        example_EnumMessage message = example_EnumMessage_init_zero;
        message.status = test_values[i];
        
        pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
        
        if (!pb_encode(&ostream, example_EnumMessage_fields, &message)) {
            printf("Encoding failed: %s\n", PB_GET_ERROR(&ostream));
            return 1;
        }
        
        message_length = ostream.bytes_written;
        
        example_EnumMessage decoded = example_EnumMessage_init_zero;
        pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
        
        if (!pb_decode(&istream, example_EnumMessage_fields, &decoded)) {
            printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
            return 1;
        }
        
        handle_status(decoded.status);
    }
    
    return 0;
}

Key points

When to use enums

Expected output

example.txt
Encoded 2 bytes
Encoded data: 08 01 
Decoded value:
  status: OK (enum value: 1)

Expected output (switch example)

example.txt
Handling status: UNKNOWN - Default state
Handling status: OK - Operation successful
Handling status: ERROR - Operation failed
Handling status: BUSY - System busy

Differences from C++

The C version is nearly identical to the C++ version:

example.txt

## More NanoPB posts

- [Basic scalar types in C++](/2026/05/09/nanopb-cpp-basic-scalar-types/)
- [Basic scalar types in C](/2026/05/09/nanopb-c-basic-scalar-types/)
- [String types in C++](/2026/05/09/nanopb-cpp-string-types/)
- [String types in C](/2026/05/09/nanopb-c-string-types/)
- [Bytes types in C++](/2026/05/09/nanopb-cpp-bytes-types/)
- [Bytes types in C](/2026/05/09/nanopb-c-bytes-types/)
- [Optional fields in C++](/2026/05/09/nanopb-cpp-optional-fields/)
- [Optional fields in C](/2026/05/09/nanopb-c-optional-fields/)
- [Repeated fields/arrays in C++](/2026/05/09/nanopb-cpp-repeated-fields/)
- [Repeated fields/arrays in C](/2026/05/09/nanopb-c-repeated-fields/)
- [Enums in C++](/2026/05/09/nanopb-cpp-enums/)
- [Nested messages in C++](/2026/05/09/nanopb-cpp-nested-messages/)
- [Nested messages in C](/2026/05/09/nanopb-c-nested-messages/)
- [Oneof/union types in C++](/2026/05/09/nanopb-cpp-oneof-types/)
- [Oneof/union types in C](/2026/05/09/nanopb-c-oneof-types/)
- [Custom array converters in C++](/2026/05/09/nanopb-cpp-custom-array-converters/)
- [Custom array converters in C](/2026/05/09/nanopb-c-custom-array-converters/)

Check out similar posts by category: Embedded, C/C++, Protocol Buffers