MATLAB: Mapping a fixed bit structure into Matlab variables

MATLABstructures

How do I map a few binary words containing sub-words (various bit lengths/types/locations) into Matlab variables? The binary data is generated externally to Matlab in fixed length blocks (8 words), as a file. Memmapfile can be used for reading the binary data from the file and it nearly does what I need except that the mapping of bits to variables names is not flexible enough. For example, suppose the 3rd word contains a signed integer from Bit 7 to Bit 12 and the 5th word contains an unsigned integer in Bit 9 to Bit 17. Is there an efficient way to map these into Matlab so that I can handle them directly as variables? In 'C' it could be done by using a UNION. Is there anything similar in Matlab? Thanks!

Best Answer

memmapfile() only goes down as as far as bytes, and not bits. fread() and fwrite() are the only Matlab I/O operators that can work at the bit level.
By the way, in C it would be struct rather than union that you would use. Each element of a C union starts at the exact same memory address right down to the bit level. Bit level representation with C's struct are not fully portable, as C does not define which "end" of a word the bits start packing from. C does define that the next bitfield should be in the same "word" as long as there is room for it, but since it doesn't define the size of words, a field you thought was in the middle of a word might be interpreted by C as being in the next word.
Thus anything that Mathworks did to work with bits would have to be incompatible with some C compiler, since Mathworks would have to assign fixed behaviour to matters C does not assign fixed behaviour to.