Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

defining a 10-bit data type

Status
Not open for further replies.

sedawk

Programmer
Feb 5, 2002
247
US
Hi,

What is the best way to define a 10-bit data type (unsigned)? To make it more robust, how to make a data type with variable length (11-bit, 21-bit etc)?

Thanks
 
If it's unsigned, I guess it's a number. What's wrong with a regular int?

Cheers,
Dian
 
unsigned x:10;

Beware of packing/unpacking problems. You can also just use an unsigned short and and it with 0x3FF. The generated code from these odd sizes can be quite complicated, depending on the compiler and the compiler writer's knowledge of the instruction set.

If you have something like
Code:
struct {
   unsigned one:10;
   unsigned two:10;
   unsigned three:12;
} fred;
fred.one = 1;
fred.two = 29;
fred.three = fred.one * fred.two;
you'll find that it generates more code than declaring them as 3 shorts. That generates more code than declaring them as 3 ints. In short, it is a false saving unless you have tons of data, otherwise what you gain in declaration space, you lose in coding.
 
A regular int has 16-bit long. If I need a 21-bit unsigned, a regular int isn't enough while it is enough for a 10-bit long unsigned.
 
sedawk said:
A regular int has 16-bit long
On a 16-bit OS like DOS maybe. Every modern OS these days has 32-bit ints.
 
Oops, right int has 32-bit long. Anyway, you get my point: I don't care much about the packing issue since I mainly use it for modeling. Coding efficiency is not very important in this regard.

Thanks
 
xwb,

what compiler you use for unsigned x:10?
 
It has to be a part of a structure. eg
Code:
struct {
   unsigned x:10;
   unsigned y:11;
   unsigned z:11;
} coords;
It should work on any C compiler. This facility has always been available in C.
 
Bit fields are not robust, portable and memory-save constructs in C and C++. It's a surrogate of true bit strings...
 
As ArkM says, they are not portable.
Code:
struct {
   unsigned whatever:10;
   unsigned whenever:10;
} bitpat;
whatever could be either the MS or LS 10 bits, again depending on compiler. They could be declared in reverse internally.
 
if you define the aim of this, maybe we could be better at explaining you why you should go with standard length data types?

------------------
When you do it, do it right.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top