进制转换c++代码_C代码实现16位和32位数据字节序转换
时间: 2024-03-06 20:48:31 浏览: 107
进制转换-不同位数的数据相互转换(C/C++实现)
进制转换C++代码:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// 10进制转2进制
string dec2bin(int n) {
string res = "";
while (n) {
res = to_string(n % 2) + res;
n /= 2;
}
return res;
}
// 2进制转10进制
int bin2dec(string s) {
int res = 0;
for (int i = 0; i < s.size(); i++) {
res = res * 2 + (s[i] - '0');
}
return res;
}
// 16进制转10进制
int hex2dec(char c) {
if ('0' <= c && c <= '9') {
return c - '0';
} else {
return c - 'A' + 10;
}
}
// 16进制转2进制
string hex2bin(char c) {
int n = hex2dec(c);
return dec2bin(n);
}
// 10进制转16进制
char dec2hex(int n) {
if (n < 10) {
return n + '0';
} else {
return n - 10 + 'A';
}
}
// 2进制转16进制
char bin2hex(string s) {
int n = bin2dec(s);
return dec2hex(n);
}
int main() {
int n = 233;
cout << dec2bin(n) << endl;
string s = "11101001";
cout << bin2dec(s) << endl;
char c = 'A';
cout << hex2dec(c) << endl;
cout << hex2bin(c) << endl;
cout << dec2hex(n) << endl;
string s2 = "11101001";
cout << bin2hex(s2) << endl;
return 0;
}
```
16位和32位数据字节序转换C代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
uint16_t swap16(uint16_t x) {
return (x << 8) | (x >> 8);
}
uint32_t swap32(uint32_t x) {
return (x << 24) |
((x << 8) & 0x00ff0000) |
((x >> 8) & 0x0000ff00) |
(x >> 24);
}
int main() {
uint16_t x16 = 0x1234;
uint32_t x32 = 0x12345678;
printf("%04x\n", x16);
printf("%08x\n", x32);
x16 = swap16(x16);
x32 = swap32(x32);
printf("%04x\n", x16);
printf("%08x\n", x32);
return 0;
}
```
阅读全文