View Single Post
Old 08-13-2008, 11:26 AM   #2 (permalink)
Thumbs Must Hurt
Join Date: Apr 2006
Location: Boston
Model: 8900
Carrier: AT&T
Posts: 98
Post Thanks: 0
Thanked 0 Times in 0 Posts


So, Java isn't really meant to do the same kind of bit-level stuff that C does (C is great for doing both high-level and low-level kinds of data manipulation; Java sort of intentionally avoided that). "Packing" (making sure your code is being economical - "stingy" - in its use of byte-space) is a concept that normally doesn't happen in Java. You can do all kinds of entertaining bit-math: you could have a private 32-bit member variable that contains the combined field1/field2/field3, doing the necessary/appropriate bit-math games for each of them (multiplying the input parameter in "setField1( int newValue )" by 2^12, etc., remembering to worry about the sign bit) to put their values into the right bit-positions, and then remembering to undo the math games when it comes time to extract the information. But that will be a significant - and rather not-easy-to-read - coding.

So you may really want to sit back and think about why you want to maintain a C-based approach when using Java. Do you need to transport the information between a C-based application and a Java-based one? If so, assuming you cannot modify the C-based application, parse data coming into the Java-based app into a class that separates the field1,2,3 information into separate member variables, and reconfigure (combine) the data when you're sending it back out. That way you can make use of the data within the Java application as is appropriate for a Java application, and keep the translation (conversion of 32-bit incoming data to 3 separate member variables, and vice-versa for outgoing data) limited to only app-boundary crossing (in other words, your conversion code only happens when data is entering from the C-app or exiting from the Java-app).

Converting the fields in your structure is fairly straightforward - Java's bit-manipulation syntax is identical to C's. There are some things to worry about (all Java integer types are signed), but they are pretty minimal and easily handled. Search on Google for "Java bit operations" and you should find quite a few tutorials and references online.

Good luck!


Karl G. Kowalski
Owns a RAZR
Develops for BlackBerry
So next phone will iPhone 3G!
Offline   Reply With Quote