简体   繁体   中英

Java 16 bit alignment

I'm currently dealing with some integer values that represent offsets within a file, the numbers I have need to be aligned on 16-bit boundaries, however I'm a little unsure how to do this.

For example:

First number: 89023
16-bit aligned: 89024

Second number: 180725
16-bit aligned: 180736

Third number: 263824
Already 16-bit aligned, don't need to change it.

This is probably my maths failing me more than anything, but if anyone could advise on how to achieve this in Java, I'd appreciate it.

Thanks!

Update

I think I've just solved it, it's just a matter of modding the value with 16, then working out what's missing from 16.

So for example:

180725 % 16 = 5
16 - 5 = 11
180725 aligned to 16-bits is: 180736

Can someone just confirm that I'm doing that correctly?

Yes that will work. The 16 bit boundary alignment just assures it will be on a multiple of 16. What you are doing there is ensuring that the value hits at the next value of 16, rounded up.

// find how far off of alignment you are, 0-15
offset = num % 16 
// determine how much further you need to move the value to achieve 16 bit alignment
// only use if offset > 0, otherwise you are already good
val = 16 - offset

Two possibilities have been described in the other answer/comment. Here are the full implementations:

public static int getAlignment_modulus() {
    int offset = num % 16;
    int result = offset == 0 ? num : num + 16 - offset;
    return result;
}

public static int getAlignment_bitOps() {
    return (num + 15) & ~15;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM