Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit fields in Scala

How to simulate bit fields in Scala? The bit fields are used to access some bits of one type (like this in C link). I know it's possible to write with bit operators, but I think there a better way if not consider the performance.

Thanks for every hint that might give.

like image 553
adelarsq Avatar asked Oct 19 '10 00:10

adelarsq


1 Answers

If you just want single bits, then collection.BitSet will work for you.

If you want a proper bit field class, then you're out of luck for two reasons. First, because Scala doesn't have one. Second, because even if it did, the space savings would probably not be very impressive since the overhead of the enclosing object would probably be large compared to your bits.

There are a couple of ways out of this with some work: a custom-defined class that wraps an integer and lets you operate on parts of it as bit fields; when you go to store the integer, though, you just have it saved as a primtive int. Or you could create an array of bit field structs (of arbitrary length) that are implemented as an array of integers. But there's nothing like that built in; you'll have to roll your own.

like image 73
Rex Kerr Avatar answered Nov 15 '22 06:11

Rex Kerr