ZCBOR encode a key as a numeric value and not a character string

Hello,

I want to encode a key as a numeric value instead of a string using the ZCBOR library.

I've tried testing this, but each time, the key is converted to a string.

uint8_t cbor_payload[200] = {0};

ZCBOR_STATE_E(encoding_state, 3, cbor_payload, sizeof(cbor_payload), 0);

uint32_t ints[1] = {1};

char var[] = "test";

bool ok = zcbor_map_start_encode(encoding_state, 10);

ok &= zcbor_uint32_encode(encoding_state, ints) &&

       zcbor_tstr_put_term(encoding_state, var, strlen(var));

ok &= zcbor_map_end_encode(encoding_state, 10);

Output: {"1":"test"}

I'd like to have {1:"test"} instead.

Is there a function that can do this?

Looking forward to hearing from you,

Sincerely,

  • HI Jp, 
    Could you try to use zcbor_uint32_put() instead of zcbor_uint32_encode()? 

    I'm not so familiar with zcbor library but as far as I know zcbor_uint32_encode() usually not used directly. 

  • Hi,

    I tried using zcbor_uint32_put() but I still get the same result.

    uint8_t cbor_payload[200] = {0};

    ZCBOR_STATE_E(encoding_state, 3, cbor_payload, sizeof(cbor_payload), 0);

    char var[] = "test";

    ok = zcbor_map_start_encode(encoding_state, 10);
    ok &= zcbor_uint32_put(encoding_state, 20) &&
    zcbor_tstr_put_term(encoding_state, var, strlen(var));
    ok &= zcbor_map_end_encode(encoding_state, 10);

    Output : {"20":"test"}.

    Do you have another solution?

  • Hi,

    Could you please provide a project with the code so I can test here ? Which SDK version did you use ?
    I'm not so familiar with the CBOR library ,Just want to be sure we are aligned. 

  • Hi,

    I'm using the latest SDK version : 3.0.2.

    Actually, once I've encoded the message, I send it via the UART serial connection and I decode the message via an application developed in C# with Visual Studio.

    This is how I get the decoding. Because if I decode the message with the zcbor_map_decode_bulk function, it doesn't work because the key must be a string, and I haven't found a function that can set a key to numeric.

    ZCBOR_STATE_D(decoding_state, 3, cbor_payload, sizeof(cbor_payload), 10, 0);

    struct zcbor_string name = { 0 };

    uint64_t var3 = 0; size_t decoded;

    struct zcbor_map_decode_key_val fs_download_decode[] = { ZCBOR_MAP_DECODE_KEY_DECODER(1, zcbor_tstr_decode, &name), ZCBOR_MAP_DECODE_KEY_DECODER("var3", zcbor_uint64_decode, &var3), };

    ok = zcbor_map_decode_bulk(decoding_state, fs_download_decode, ARRAY_SIZE(fs_download_decode), &decoded) == 0;

    How can I send my project? I couldn't attach it.

  • Hi,
    You can click on the Upload button to attach the file. Or click Insert -> Image/video/File

Related