Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
展示存储 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
You can’t perform that action at this time.