我有一个九位数的数组,范围为0-999,999,999。我希望能够将它们解析为Colors数组。然后,我希望能够将颜色数组转换回数字数组。
这就是我想要做的:
Color[] colors = encode(intEnter);//intEnter is any integer which is 8 or 9 characters long.
int decode = decode(colors);//returns intEnter
我想做新的Color(999,999,999),但它最多支持255。
如何创建一个颜色数组来编码比rgb支持的数字更大的数字,然后将其解码回去?
与其组合3个字节以形成9位整数,不如使用3个字节来创建颜色。你必须先unsign他们,虽然,以抵消范围0
来255
,而不是-128
到127
。
假设您有一个byte[]
大小为100_000
满字节的:
byte[] bytes = new byte[100_000];
new Random().nextBytes(bytes); //fills array with bytes; simulates bytes from stream
无符号字节值不能适合byte
,因此我们必须使用short[]
或int[]
。要将带符号的字节转换为无符号的字节,我们使用按位&
对255
(通常称为0xff
):
int[] unsign(byte[] bytes) {
int[] unsignedBytes = new int[bytes.length];
for(int i = 0; i < unsignedBytes.length; i++) {
unsignedBytes[i] = bytes[i] & 0xff;
}
return unsignedBytes;
}
要将这些分组为3s,我们首先需要确保将字节数除以3。例如,如果我们有个数组[101, 74, 88, 21]
,则可以删除21
来创建颜色,也可以添加20
来创建2种颜色。 。第一种选择会导致数据丢失,因此我们将选择第二种选择:
int[] sizeArray(int[] unsignedBytes) {
int length = unsignedBytes.length;
int bytesPerColor = 3;
int remainder = length % bytesPerColor;
int bytesNeeded = bytesPerColor - remainder;
int numOfBytes = remainder > 0 ? length + bytesNeeded : length;
int[] sizedArray = new int[numOfBytes];
System.arrayCopy(unsignedBytes, 0, sizedArray, length);
return sizedArray;
}
现在进行编码。每3个字节,我们就会生成一种颜色:
Color[] encode(int[] unsignedBytes) {
Color[] colors = new Color[unsignedBytes.length / 3];
for(int i = 0, position = 0; i < colors.length; i++) {
int r = unsignedBytes[position++];
int g = unsignedBytes[position++];
int b = unsignedBytes[position++];
colors[i] = new Color(r, g, b);
}
return colors;
}
要进行解码,只需从每种颜色中获取RGB值:
int[] decode(Color[] colors) {
int[] unsignedBytes = new int[colors.length * 3];
int position = 0;
for(Color color : colors) {
unsignedBytes[position++] = color.getRed();
unsignedBytes[position++] = color.getGreen();
unsignedBytes[position++] = color.getBlue();
}
return unsignedBytes;
}
要对字节进行签名,只需将其转换回字节即可:
byte[] sign(int[] unsignedBytes) {
byte[] signedBytes = new byte[unsignedBytes.length];
for(int i = 0; i < signedBytes.length; i++) {
signedBytes[i] = (byte) unsignedBytes[i];
}
return signedBytes;
}
您可以有一个Encoder
andDecoder
类,如果需要,可以为您进行签名和取消签名:
class Encoder {
public Color[] encode(byte[] signedBytes) {
return encode(unsign(signedBytes));
}
public Color[] encode(int[] unsignedBytes) {
//...
}
private int[] unsign(byte[] signesBytes) {
//...
}
}
class Decoder {
public byte[] decode(Color[] colors) {
//receive unsigned bytes from colors
return sign(unsignedBytes);
}
private byte[] sign(int[] unsignedBytes) {
//...
}
}
用手机写了这个,所以如果有什么问题请告诉我
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句