B4J Question How to access byte array as int/short value directly without overhead?

kimstudio

Active Member
Licensed User
Longtime User
Is it possible to directly mapping an int() to byte array? then the byte array can be accessed as int values.

For instance, int(0) will be b(0), b(1), b(2), b(3) and int(1) will be b(4) to b(7). In C/C++ this can be achieved by an int pointer pointed to a memory space where byte() stored. ByteConverter can do this but for repeated conversion tasks like bitmap frame refreshing every certain milliseconds I am not sure whether the internal conversion may bring some overhead? Also bit.shift or multiply/add from 4 bytes to make an int will also lead to some overhead. Thanks.
 

kimstudio

Active Member
Licensed User
Longtime User
Thanks agraham. I digged the ByteConverter thread and found the thin wrap in the source code as you indicated:

IntBuffer ib = ByteBuffer.wrap(bytes).order(endian).asIntBuffer();

Not sure Internally how it works but looks mostly like the C/C++ pointer concept, that's great.

Maybe I am too obsessed to one or two milliseconds faster which I should not concern for modern computers :)
 
Upvote 0

teddybear

Well-Known Member
Licensed User
Maybe I am too obsessed to one or two milliseconds faster which I should not concern for modern computers :)
If you are doing CV, it is worth actively considering reducing the overhead
 
Upvote 0

emexes

Expert
Licensed User
IntBuffer ib = ByteBuffer.wrap(bytes).order(endian).asIntBuffer();

Not sure Internally how it works but looks mostly like the C/C++ pointer concept, that's great.

Use one of the function calls to "map" Bytes to Ints, and then see if changes to one are reflected by changes in the other, ie are they using the same memory locations?

If not, then the Java function is allocating and copying memory, and no degree of wrapper thinness is going to magic that away.

Although, speaking of magic, I do recall that MMUs can make one area of memory look like two (subject to page address alignment) and defer the allocation and copying until changes (writes) are made to one of the "duplicated" memory pages.

edit: I also vaguely recall being able to memory-map files as arrays under VAX VMS, and I believe what it did was map the file pages as paged-out memory pages, and then later the file would read from disk by the usual virtual memory handler when the array was accessed, no extra effort required.
 
Last edited:
Upvote 0

emexes

Expert
Licensed User
I may play with ByteBuffer later.

There is also potentially another roadbump on your quest for ultimate efficiency, being that I suspect multi-dimensional arrays are actually arrays of arrays of elements, rather than a single contiguous block of all the elements.

I should probably check this out before casting aspersions (lol no pun intended), but I figure: let's see how long it takes for me to be corrected (if I'm wrong). ?
 
Upvote 0
Top