Last active
June 7, 2019 03:00
展示存储 Float 浮点型数据的具体结构
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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