BlackBerry Forums Support Community

BlackBerry Forums Support Community (
-   Developer Forum (
-   -   C conversion issue (

op1984 08-13-2008 10:39 AM

C conversion issue
I'm working on a converting a c program to java for the blackberry and I was wondering what is the best way to convert the following c snippet to java.


        typedef struct foo
                unsigned int field1:12;
                unsigned int field2:4;
                unsigned int field3:16;

I was going to create a class to encapsulate everything however getting the data packed into a byte array correctly is bothering me. I know it's going to involve some bit shifting but i have no idea how to do it at the moment.

Any ideas,

holy3daps 08-13-2008 11:26 AM


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!



All times are GMT -5. The time now is 11:04 AM.

Powered by vBulletin® Version 3.6.12
Copyright ©2000 - 2018, Jelsoft Enterprises Ltd.