首页 > 编程知识 正文

C/C++ 十进制转16进制

时间:2023-05-04 03:03:46 阅读:271421 作者:1461

把一个十进制的数转换成16进制其实不难,但是我在实现的时候也折腾了会。

首先贴一个LeetCode上面的一个题目和C++解法。

Convert a Number to Hexadecimal
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

Note:

All letters in hexadecimal (a-f) must be in lowercase.
The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character ‘0’; otherwise, the first character in the hexadecimal string will not be the zero character.
The given number is guaranteed to fit within the range of a 32-bit signed integer.
You must not use any method provided by the library which converts/formats the number to hex directly.

const string HEX = "0123456789abcdef";class Solution {public: string toHex(int num) { if (num == 0) return "0"; string result; int count = 0; while (num && count++ < 8) { result = HEX[(num & 0xf)] + result; num >>= 4; } return result; }};

上面的方法的意思就是一个int是一个32位的有符号的数,通过8次转换成16进制,因为一位16进制的数最大F,也就是2^4。
每一次操作的时候跟0x0F做与操作的意思就是取最低的4位,然后在0~F中间匹配即可得到这一位的十六进制。

接下来再看一个写法,意思和上面一样。

const char * hex = "0123456789ABCDEF";char output[] = "0x00000000";int value = 0x89ABCDEF;for(int i = 0; i < 8; i++){ output[9 - i] = hex[(value >> i * 4) & 0x0F];}

如果一个int没有那么大,你也知道得到的hex的数据长度,那么上面的代码就可以简化了。比如我知道每一次我需要转化的int得到的hex长度只有两位,那就可以简化上面的代码。

void DectoHex(int dec, unsigned char *output, int length) { const char * hex = "0123456789ABCDEF"; for (int i = 0; i<length; i++) { output[length - i -1] = hex[(dec >> i * 4) & 0x0F]; } }

上面的length表示得到的hex的长度。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。