Skip to content

Instantly share code, notes, and snippets.

@QuincySx
Last active June 7, 2019 03:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save QuincySx/1d22e660124cc9f661b2528379f5af9b to your computer and use it in GitHub Desktop.
Save QuincySx/1d22e660124cc9f661b2528379f5af9b to your computer and use it in GitHub Desktop.
展示存储 Float 浮点型数据的具体结构
public void showFloatBits(float floatNumber) {
var FLOAT_BYTE_SIZE = 4;
var BYTE_BIT_SIZE = 8;
var FLOAT_SYMBOL_POSITION = 1;
var FLOAT_MANTISSA_POSITION = 10;
var byteBuffer = ByteBuffer.allocate(FLOAT_BYTE_SIZE);
byteBuffer.putFloat(floatNumber);
var numberByteArray = byteBuffer.array();
var buffer = new String[FLOAT_BYTE_SIZE * BYTE_BIT_SIZE + 2];
var bitPosition = 0;
for (int i = 0; i < FLOAT_BYTE_SIZE; i++) {
for (int j = 0; j < BYTE_BIT_SIZE; j++) {
buffer[bitPosition] = String.valueOf(numberByteArray[i] >> (BYTE_BIT_SIZE - j - 1) & 0B1);
bitPosition++;
// 位置标识分开符号、指数和尾数
if (bitPosition == FLOAT_SYMBOL_POSITION || bitPosition == FLOAT_MANTISSA_POSITION) {
buffer[bitPosition] = "-";
bitPosition++;
}
}
}
Arrays.stream(buffer).forEach(System.out::print);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment