在字节数组上进行正确的位旋转/循环移位的最快方法是什么 [英] What's the fastest way to do a right bit rotation/circular shift on a byte array

查看:74
本文介绍了在字节数组上进行正确的位旋转/循环移位的最快方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有数组:

{01101111,11110000,00001111} // {111, 240, 15}

移位1位的结果是:

{10110111,11111000,00000111} // {183, 248, 7}

数组大小不是固定的,并且移位范围是从1到7(包括1和7).目前,我有以下代码(效果很好):

The array size is not fixed, and the shifting will be from 1 to 7 inclusive. Currently I have the following code (which works fine):

private static void shiftBitsRight(byte[] bytes, final int rightShifts) {
   assert rightShifts >= 1 && rightShifts <= 7;

   final int leftShifts = 8 - rightShifts;

   byte previousByte = bytes[0]; // keep the byte before modification
   bytes[0] = (byte) (((bytes[0] & 0xff) >> rightShifts) | ((bytes[bytes.length - 1] & 0xff) << leftShifts));
   for (int i = 1; i < bytes.length; i++) {
      byte tmp = bytes[i];
      bytes[i] = (byte) (((bytes[i] & 0xff) >> rightShifts) | ((previousByte & 0xff) << leftShifts));
      previousByte = tmp;
   }
}

是否有比当前方法更快的方法?

Is there a faster way to achieve this than my current approach?

推荐答案

找出唯一的方法是使用彻底的基准测试,并且最快的实现将因平台而异.如果您确实需要优化此工具,请使用 Caliper 之类的工具.

The only way to find out is with thorough benchmarking, and the fastest implementations will vary from platform to platfrm. Use a tool like Caliper if you really need to optimize this.

这篇关于在字节数组上进行正确的位旋转/循环移位的最快方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆