I have little unusual problem to solve. I need some hint or links to get started with. I have queue with 10 data slots. Once the queue is full I need to send it to a server. However, along with that data, I also send start and end sequence number. Now, this numbers must be unique and in increment order. So, for the first send, start = 1, and end = 10. On second send, it would be start = 11, end = 20, and so on. Once the data from the queue is send, new entries will be recorded from the index 0 in the queue.
How do I solve this efficiently ?
(There is a lot of context missing from your question, so this is mostly a shot in the dark…)
Since any 16-bit number can fit in a Java
intprimitive, you can:Convert a Java
intto a 16-bit number by ANDing the number with a suitable bitwise mask:WARNING: This conversion is lossy and not easily reversible.
Convert a 16-bit number to a 32-bit
intby keeping a separate epochintthat is incremented by one on each roll-over:I do not think that it can get much more efficient than that in Java. Not to mention that any CPU that can run Java would normally run circles around any 16-bit processor, except perhaps for some DSPs…
A couple of related concerns:
Beware of signed/unsigned conversions: Java does not have unsigned types, which may complicate things, depending on what exactly your are doing.
Please note that, according to the JLS, the
byte,charandshortprimitive types are implicitly converted tointfor all operations. Whether they are actually narrower than 32-bits when stored in memory is implementation specific. And yes, that makes theshorttype pretty much useless…