views:

131

answers:

3
+1  Q: 

Custom byte size?

So, you know how the primitive of type char has the size of 1 byte? How would I make a primitive with a custom size? So like instead of an in int with the size of 4 bytes I make one with size of lets say 16. Is there a way to do this? Is there a way around it?

+1  A: 

It depends on why you are doing this. Usually, you can't use types of less than 8 bits, because that is the addressable unit for the architecture. You can use structs, however, to define different lengths:

struct s {
  unsigned int a : 4;  // a is 4 bits
  unsigned int b : 4;  // b is 4 bits
  unsigned int c : 16; // c is 16 bits
};

However, there is no guarantee that the struct will be 24 bits long. Also, this can cause endian issues. Where you can, it's best to use system independent types, such as uint16_t, etc. You can also use bitwise operators and bit shifts to twiddle things very specifically.

WhirlWind
uint16_t still has endian issues.
Billy ONeal
@Billy true... I guess my point is that bitfields in structs are very messy in this regard, and that's one of their primary uses.
WhirlWind
@WhirlWind: Yep. I wasn't gonna downvote you for it. But I did think it was worth mentioning.
Billy ONeal
+4  A: 

Normally you'd just make a struct that represents the data in which you're interested. If it's 16 bytes of data, either it's an aggregate of a number of smaller types or you're working on a processor that has a native 16-byte integral type.

If you're trying to represent extremely large numbers, you may need to find a special library that handles arbitrarily-sized numbers.

Dan Olson
A: 

If you want to make a new type, typedef it. If you want it to be 16-bytes in size, typedef a struct that has 16-bytes of member data within it. Just beware that quite often compilers will pad things on you to match your systems alignment needs. A 1 byte struct rarely remains 1 bytes without care.

Michael Dorgan