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.
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.
|All times are GMT -5. The time now is 07:42 AM.|
Powered by vBulletin® Version 3.6.12
Copyright ©2000 - 2016, Jelsoft Enterprises Ltd.