Reputation: 2265
I have a byte array which can have up to 4000 elements. These elementes can be byte/boolean(1 byte) int(2 byte) or long/float(4byte). They are not mixed, so one byte array only contains one data type
If the array changes I want to get the position which is affected.. but if arr[5] changes, it is for example the second real value which has changed! but if it is a boolean it is the 6th value.
so far I have done this
private void diff(byte[] a, byte[] b){
if (a.length == b.length) {
for (int i = 0; i < getCount(); i++) {
if (!get(MyType.real,i, b).equals(get(MyType.real,i, a))) {
//difference
}
}
this.data = data;
}
}
private Object get(MyType type, int idx, byte[] data) {
logger.entry(idx, data);
ByteBuffer buffer = ByteBuffer.wrap(data)
.order(ByteOrder.LITTLE_ENDIAN);
switch (type) {
case BOOL:
return logger.exit(buffer.get(idx) > 0);
case DWORD:
return logger.exit(buffer.asIntBuffer().get(idx));
case INT:
return logger.exit(buffer.asShortBuffer().get(idx));
case REAL:
return logger.exit(buffer.asFloatBuffer().get(idx));
case TIME:
return logger.exit(buffer.asIntBuffer().get(idx));
default:
return logger.exit(buffer.get(idx));
}
}
but this takes quite a while. Any Ideas to improve the performance?
Upvotes: 0
Views: 1597
Reputation: 676
I think your code is too complicated. You could find the absolute position of the difference and then divide it by the size of the array type.
Example code:
private int diffpos(byte[] a, byte[] b, int typeLenght){
if (a.length == b.length) {
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
return i / typeLenght;
}
}
}
return 0;
}
Upvotes: 1
Reputation: 328850
Find the first difference by comparing bytes and then divide this index by the size of a single element in the buffer:
int pos = findFirstDifference(a, b);
pos /= type.elementSize();
Upvotes: 0