4 ms·
One complaint I've always had that no one else seems to bring up: I can't take a flat array of bytes and map a struct over it. You have to fake that out in the
by mynameishere 19y ago
One complaint I've always had that no one else seems to bring up: I can't take a flat array of bytes and map a struct over it. You have to fake that out in the most lamentable way...
I guess most people don't need to do that anymore.
- Tichy 19y agoI guess you are right, because I don't even understand what you mean?
- mynameishere 19y agostruct MyStruct { int a; } ; char bytes[]={0,1,0,0}; MyStruct *myStruct=((MyStruct [asterisk] )bytes); ...myStruct->a is now 256. How do you format code here?
- Tichy 19y agoI see - I am glad that Java does not support that ;-) Presumably what you want can be achieved with ByteArrayInputStream and DataInputStream. byte[] bytes = {0,1,0,0}; DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes)); int a = in.readInt(); in.close(); untested, but something like that... There is also object serialization. I never had a use case for what you describe. (format code with 4 leading spaces)
- mynameishere 19y agoGuess how many CPU cycles my C code requires.
- Tichy 19y agoWhat time sensitive operation requires you to transform byte arrays into objects? I assumed something like reading from disk or network, and then CPU cycles are usually not the bottleneck. Anyway, no doubt that you can write faster code in C, but I am glad that I did not have to look at pointer arithmetic for the last 8 years. Using your array->struct technique would be a major headache if the struct get's more complex.
- boucher 19y agoThere are plenty of other practical use cases for this kind of control. For example, casting an array of byte[]s to an array of int[]s. It's not hard to convert using a ByteBuffer, but its still annoying. You and up duplicating a ton of memory for no good reason.
- boucher 19y agoobject serialization is horribly inefficient in java.
- brlewis 19y agoYou're assuming a 32-bit little-endian system. Indent at least two spaces for code.
- Goladus 19y agoHe wants fine control over memory allocation. Most people who want that much control use C or C++.
- tlrobinson 19y agoIt's also annoying that there aren't any unsigned (primitive) data types in Java. You end up doing weird bitwise operations to get the correct results. for example, to convert an unsigned byte to an integer: byte a = (some unsigned byte data); int b = 0xff & a;