Reputation: 7349
I'm trying to check some homework answers about overflow for 2's complement addition, subtraction, etc. and I'm wondering if I can specify the size of a data type. For instance if I want to see what happens when I try to assign -128 or -256 to a 7-bit unsigned int.
Upvotes: 1
Views: 3259
Reputation: 34205
For an arbitrary sized value, you can use bitfields in structs. For example for a 7-bit value:
struct something {
unsigned char field:7;
unsigned char padding:1;
};
struct something value;
value.field = -128;
Upvotes: 1
Reputation: 849
On further reading I see you wanted bit sizes that are not normal ones, such as 7 bit and 9 bit etc. You can achieve this using bitfields
struct bits9
{
int x : 9;
};
Now you can use this type bits9
which has one field in it x
that is only 9 bits in size.
struct bits9 myValue;
myValue.x = 123;
Upvotes: 7
Reputation: 849
Using built in types you have things like:
char value1; // 8 bits
short value2; // 16 bits
long value3; // 32 bits
long long value4; // 64 bits
Note this is the case with Microsoft's compiler on Windows. The C standard does not specify exact widths other than "this one must be at least as big as this other one" etc. If you only care about a specific platform you can print out the sizes of your types and use those once you have figured them out.
Alternatively you can use stdint.h
which is in the C99 standard. It has types with the width in the name to make it clear
int8_t value1; // 8 bits
int16_t value2; // 16 bits
int32_t value3; // 32 bits
int64_t value4; // 64 bits
Upvotes: 1
Reputation: 12185
The smallest size you have have is char which is an 8 bit integer. You can have unsigned and signed chars. Take a look at the stdint.h header. It defines a int types for you in a platform independent way. Also there is no such thing as an 7 bit integer.
Upvotes: 0