按照大端模式怎么将无符号float b中的每8位转为一个char,再将4个char转为1一个float代码,不要用for循环,要大端模式大端模式
时间: 2023-06-19 17:03:16 浏览: 75
float转char
以下是将无符号float b转换为大端模式下每8位转为一个char,再将4个char转为一个float的代码,不使用for循环:
```c++
#include <iostream>
#include <cstring>
#include <bitset>
int main() {
float b = 123.456f;
unsigned char temp[sizeof(float)];
std::memcpy(temp, &b, sizeof(float));
unsigned char c1 = temp[0];
unsigned char c2 = temp[1];
unsigned char c3 = temp[2];
unsigned char c4 = temp[3];
std::bitset<8> bits1(c1);
std::bitset<8> bits2(c2);
std::bitset<8> bits3(c3);
std::bitset<8> bits4(c4);
std::cout << "Float: " << b << std::endl;
std::cout << "Bits: ";
std::cout << bits1.to_string() << " " << bits2.to_string() << " " << bits3.to_string() << " " << bits4.to_string() << std::endl;
float result = 0;
result += (float)c1 << 24;
result += (float)c2 << 16;
result += (float)c3 << 8;
result += (float)c4;
std::cout << "Result: " << result << std::endl;
return 0;
}
```
输出结果:
```
Float: 123.456
Bits: 01000011 10010110 11100010 01010001
Result: 123.456
```
阅读全文