【发布时间】:2018-02-12 02:03:21
【问题描述】:
我有一个字节数组byte bytes[],代表灰度图像。
我想反转这张图片的颜色 - 所以我想我只会翻转位(按位不)。
我已经尝试过,如下所示(包括一个额外的循环来填充一个虚拟字节数组,以便快速轻松地重新创建我的问题)
Random rand = new Random();
byte bytes[] = new byte[500];
// populate a dummy byte array
for (int i = 0; i < bytes.length; ++i)
{
new Random().nextBytes(bytes);
System.out.println(bytes[i]);
}
for (int i = 0; i < bytes.length; ++i)
{
System.out.print(bytes[i] + " ");
//bytes[i] = ~bytes[i]; This throws an error as apparantly java treats a byte array as an integer array?!
bytes[i] = (byte)~bytes[i]; // This compiles but output not a bitwise not, results displayed below
System.out.println(bytes[i]);
}
我得到的结果是:
116 -117
48 -49
70 -71
我正在寻找的是:(我已经手动添加了二进制文件,以充分说明我对按位不理解的内容(如有错误请更正)
116 (01110100) = (10001011) 139
48 (00110000) = (11001111) 207
70 (01000110) = (10111001) 185
提前感谢您的任何建议
【问题讨论】:
-
关于您的评论,Java 不会将字节数组视为 int 数组,但是当您对它们执行操作时,它会自动将更窄的类型转换为 int。是
~使它成为 int (是的,您可以直接回退)
标签: java arrays image binary bitwise-operators