简体   繁体   English

2字节数组的差异

[英]difference of 2 byte arrays

I have a byte array which can have up to 4000 elements. 我有一个字节数组,最多可以包含4000个元素。 These elementes can be byte/boolean(1 byte) int(2 byte) or long/float(4byte). 这些元素可以是byte / boolean(1个字节)int(2个字节)或long / float(4个字节)。 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! 如果数组改变了,我想得到受影响的位置。.但是如果arr [5]改变了,例如第二个实数值就改变了! but if it is a boolean it is the 6th value. 但如果是布尔值,则为第6个值。

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? 有任何改善性能的想法吗?

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;
}

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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