Byte String
CBOR major type 2 encodes byte strings (raw binary data). The argument gives the byte count followed immediately by that many bytes. 0x43 0xde 0xad 0xbe = 3-byte string 0xDEADBE. No encoding applied – bytes are transmitted as-is. This is what JSON lacks: native binary without base64.
Encoding
Major type 2 is the primary reason to choose CBOR over JSON for protocols handling binary data. JSON has no binary type – binary must be base64-encoded into a string, adding ~33% overhead. CBOR byte strings transmit raw bytes with only the length prefix overhead.
Byte strings are useful for: cryptographic keys, nonces, and signatures (COSE/FIDO2), file contents, hash values (SHA-256 = 32 bytes = 0x5820 followed by 32 bytes), IP addresses (4 or 16 bytes), and any application-specific binary.
Indefinite-length byte strings use 0x5f as the opening byte, followed by chunks each starting with a major-type-2 byte, and terminated by the break code 0xff.
Examples
| Label | Hex | Value |
|---|---|---|
| Empty | 40 | 0 bytes |
| 0xDEADBEEF | 44 de ad be ef | 4 bytes |
| SHA-256 hash | 58 20 [32 bytes] | 32-byte hash |
| IPv4 address | 44 c0 a8 01 01 | 192.168.1.1 in 4 bytes |