短时间内替换多个位
Replace multiple bits in a short
如何在 Java 中替换短的多个位?
我正在研究一种加密算法,我需要执行以下操作:
我短路了,需要应用一系列 4 位替换。
示例:如果前4位是0010
,则替换为0110
,如果是1111
,则替换为1100
等,后4位相同.
best/fastest 的方法是什么?目前我将 short 转换为 String 并用 String 替换来完成它,但它显然非常慢,在我看来绝对是错误的方式。
位运算,类似这样:
short s = 191;
short first = (short) (s & 0x000F);
short second = (short) ((s >> 4) & 0x000F);
short third = (short) ((s >> 8) & 0x000F);
short fourth = (short) ((s >> 12) & 0x000F);
call_the_method_to_convert_each();
s = fourth;
s = ((short) ((s << 4) | third));
s = ((short) ((s << 4) | second));
s = ((short) ((s << 4) | first));
如何在 Java 中替换短的多个位?
我正在研究一种加密算法,我需要执行以下操作:
我短路了,需要应用一系列 4 位替换。
示例:如果前4位是0010
,则替换为0110
,如果是1111
,则替换为1100
等,后4位相同.
best/fastest 的方法是什么?目前我将 short 转换为 String 并用 String 替换来完成它,但它显然非常慢,在我看来绝对是错误的方式。
位运算,类似这样:
short s = 191;
short first = (short) (s & 0x000F);
short second = (short) ((s >> 4) & 0x000F);
short third = (short) ((s >> 8) & 0x000F);
short fourth = (short) ((s >> 12) & 0x000F);
call_the_method_to_convert_each();
s = fourth;
s = ((short) ((s << 4) | third));
s = ((short) ((s << 4) | second));
s = ((short) ((s << 4) | first));