1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 18 package com.android.internal.util; 19 20 import android.annotation.Nullable; 21 22 import libcore.util.Objects; 23 24 import java.util.Arrays; 25 import java.util.UUID; 26 27 public class BitUtils { BitUtils()28 private BitUtils() {} 29 maskedEquals(long a, long b, long mask)30 public static boolean maskedEquals(long a, long b, long mask) { 31 return (a & mask) == (b & mask); 32 } 33 maskedEquals(byte a, byte b, byte mask)34 public static boolean maskedEquals(byte a, byte b, byte mask) { 35 return (a & mask) == (b & mask); 36 } 37 maskedEquals(byte[] a, byte[] b, @Nullable byte[] mask)38 public static boolean maskedEquals(byte[] a, byte[] b, @Nullable byte[] mask) { 39 if (a == null || b == null) return a == b; 40 Preconditions.checkArgument(a.length == b.length, "Inputs must be of same size"); 41 if (mask == null) return Arrays.equals(a, b); 42 Preconditions.checkArgument(a.length == mask.length, "Mask must be of same size as inputs"); 43 for (int i = 0; i < mask.length; i++) { 44 if (!maskedEquals(a[i], b[i], mask[i])) return false; 45 } 46 return true; 47 } 48 maskedEquals(UUID a, UUID b, @Nullable UUID mask)49 public static boolean maskedEquals(UUID a, UUID b, @Nullable UUID mask) { 50 if (mask == null) { 51 return Objects.equal(a, b); 52 } 53 return maskedEquals(a.getLeastSignificantBits(), b.getLeastSignificantBits(), 54 mask.getLeastSignificantBits()) 55 && maskedEquals(a.getMostSignificantBits(), b.getMostSignificantBits(), 56 mask.getMostSignificantBits()); 57 } 58 unpackBits(long val)59 public static int[] unpackBits(long val) { 60 int size = Long.bitCount(val); 61 int[] result = new int[size]; 62 int index = 0; 63 int bitPos = 0; 64 while (val > 0) { 65 if ((val & 1) == 1) result[index++] = bitPos; 66 val = val >> 1; 67 bitPos++; 68 } 69 return result; 70 } 71 packBits(int[] bits)72 public static long packBits(int[] bits) { 73 long packed = 0; 74 for (int b : bits) { 75 packed |= (1 << b); 76 } 77 return packed; 78 } 79 } 80