java - 位摆弄 : Encoding Unsigned Primitives

标签 java bit-manipulation

下面是一个类,它将无符号基元类型编码为字节数组,并将编码的字节数组返回为十进制字符串。我从概念上理解 encodeIntBigEndianbyteArrayToDecimalString 的工作原理。不过,我希望能澄清以下问题:

  1. Why/how shifting the val by ((size - i - 1) * Byte.SIZE) produces an unsigned java byte value.
  2. Also, why does applying a byte mask of 0xff convert the byte to a decimal string value.
public class BruteForceCoding {
 private static byte byteVal = 101; // one hundred and one
 private static short shortVal = 10001; // ten thousand and one
 private static int intVal = 100000001; // one hundred million and one
 private static long longVal = 1000000000001L;// one trillion and one

 private final static int BSIZE = Byte.SIZE / Byte.SIZE;
 private final static int SSIZE = Short.SIZE / Byte.SIZE;
 private final static int ISIZE = Integer.SIZE / Byte.SIZE;
 private final static int LSIZE = Long.SIZE / Byte.SIZE;

 private final static int BYTEMASK = 0xFF; // 8 bits
 public static String byteArrayToDecimalString(byte[] bArray) {
  StringBuilder rtn = new StringBuilder();
  for (byte b : bArray) {
   rtn.append(b & BYTEMASK).append(" ");
  }
  return rtn.toString();
 }

 public static int encodeIntBigEndian(byte[] dst, long val, int offset, int size) {
  for (int i = 0; i < size; i++) {
   dst[offset++] = (byte) (val >> ((size - i - 1) * Byte.SIZE));
  }
  return offset;
 }

 public static void main(String[] args) {
  byte[] message = new byte[BSIZE + SSIZE + ISIZE + LSIZE];
  // Encode the fields in the target byte array
  int offset = encodeIntBigEndian(message, byteVal, 0, BSIZE);
  offset = encodeIntBigEndian(message, shortVal, offset, SSIZE);
  offset = encodeIntBigEndian(message, intVal, offset, ISIZE);
  encodeIntBigEndian(message, longVal, offset, LSIZE);
  System.out.println("Encoded message: " + byteArrayToDecimalString(message));
 }
}

最佳答案

1)它本身并没有。它的作用是将值向下移动一个字节为单位。但是,当与丢弃高位的 (byte) 转换结合使用时,这相当于从值中提取各个字节的移位和掩码操作。

2)事实并非如此。它屏蔽掉高位,保留值的低八位(一个字节)——与前一种情况中执行的转换为字节的操作相同。但是,默认情况下,将字节呈现为字符串会生成一个包含表示其二进制值(从 0 到 255)的十进制数的字符串,并且在调用 .append() 时会隐式发生这种情况。

关于java - 位摆弄 : Encoding Unsigned Primitives,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21390542/

相关文章:

java - 是否有任何有效的方法可以保持运行方法中包含 ActionListener 的线程处于 Activity 状态,直到发生单击事件?

java - 使用 Jackson 反序列化对象 json 对象列表 - 无法从 start_array token 中反序列化实例

php - 如何测试 PHP 按位函数输入参数

c - 如何在 C 中设置 char[1024] 的第 513 位?

c - 这段代码有什么作用?

c - 数据类型范围有限

java - 服务和 DAO 总是实现接口(interface)

java - 如何在文件路径中处理 ~

java - 在 Redis 重启时自动将 Storm Topology 重新连接到 Redis Cluster

ios - 从 Objective C 转换为 Swift 后,问题位移位 UInt8