unfamiliar variable declaration in struct

Started by
2 comments, last by L. Spiro 12 years, 4 months ago
Hello

I am reading some old c++ code, from about 2003 and I noticed in a struct declaration is a colon followed by a number after the variable:


typedef struct
{
DWORD id;
long type:7;
long next:19;

.
.
.


what does it do?
Advertisement
It's called 'bit fields', and means that 'type' uses 7 bits and 'next' uses 19 bits. Google gives for example this with some examples: http://www.cs.cf.ac.uk/Dave/C/node13.html

(You should be aware bit ordering isn't guaranteed and that structures can be padded, so don't count on it giving exactly any special bit representation of the struct unless you analyze it for a specific platform and compiler).
So I am guessing it is just a way of saving a few bits of memory if you know that the variable will not exceed a certain value (4 bits are 0-15). I am guessing you can only write bytes to files, which means that the struct is padded to the next whole byte.

Also, cutting 7 bits out of a struct is pointless since it has to be padded up 7 bits again, right?
If your goal is to decrease file sizes, use bit streams instead.


L. Spiro

I restore Nintendo 64 video-game OST’s into HD! https://www.youtube.com/channel/UCCtX_wedtZ5BoyQBXEhnVZw/playlists?view=1&sort=lad&flow=grid

This topic is closed to new replies.

Advertisement