Correct datatype for working with raw memory

I have a class that makes it easy to encode / decode raw memory. I end up storing a pointer void

pointing to memory and the number of byte references. I'm worried about alias issues as well as bit shifting operations for correct encoding. Essentially, to WHAT_TYPE

be used char

, unsigned char

, int8_t

, uint8_t

, int_fast8_t

, uint_fast8_t

, int_least8_t

or uint_least8_t

? Is there a definitive answer in the spec?

class sample_buffer {
    size_t index; // For illustrative purposes
    void *memory;
    size_t num_bytes;
public:
    sample_buffer(size_t n) :
        index(0),
        memory(malloc(n)),
        num_bytes(memory == nullptr ? 0 : n) {
    }
    ~sample_buffer() {
        if (memory != nullptr) free(memory);
    }
    void put(uint32_t const value) {
        WHAT_TYPE *bytes = static_cast<WHAT_TYPE *>(memory);
        bytes[index] = value >> 24;
        bytes[index + 1] = (value >> 16) & 0xFF;
        bytes[index + 2] = (value >> 8) & 0xFF;
        bytes[index + 3] = value & 0xFF;
        index += 4;
    }
    void read(uint32_t &value) {
        WHAT_TYPE const *bytes = static_cast<WHAT_TYPE const *>(memory);
        value = (static_cast<uint32_t>(bytes[index]) << 24) |
                (static_cast<uint32_t>(bytes[index + 1]) << 16) |
                (static_cast<uint32_t>(bytes[index + 2]) << 8) |
                (static_cast<uint32_t>(bytes[index + 3]);
        index += 4;
    }
};

      

+3


source to share


1 answer


In C ++, 17: std::byte

. This type was specially created for this very reason, in order to convey all the correct semantic meaning. What's more, it has all the operators you need to use on the raw data (like <<

in your example), but none of the operators you wouldn't.




To C ++ 17: unsigned char

. The standard defines the representation of an object as a sequence unsigned char

, so this is just a good type to use. Also, as Mooing Duck correctly suggests , using will unsigned char*

prevent many errors caused by misusing yours char*

, which references the raw bytes as if it were a string and passing it to a type function strlen

.

If you really cannot use unsigned char

, then you must use char

. Both unsigned char

and char

are types that you allow the alias, so either is preferred over any other integer type.

+10


source







All Articles