C语言实现字节流与十六进制字符串的相互转换
2016-03-29 22:55
162 查看
//字节流转换为十六进制字符串 void ByteToHexStr(const unsigned char* source, char* dest, int sourceLen) { short i; unsigned char highByte, lowByte; for (i = 0; i < sourceLen; i++) { highByte = source[i] >> 4; lowByte = source[i] & 0x0f; highByte += 0x30; if (highByte > 0x39) dest[i * 2] = highByte + 0x07; else dest[i * 2] = highByte; lowByte += 0x30; if (lowByte > 0x39) dest[i * 2 + 1] = lowByte + 0x07; else dest[i * 2 + 1] = lowByte; } return; }
//字节流转换为十六进制字符串的另一种实现方式 void Hex2Str(const char *sSrc, char *sDest, int nSrcLen) { int i; char szTmp[3]; for (i = 0; i < nSrcLen; i++) { sprintf(szTmp, "%02X", (unsigned char)sSrc[i]); memcpy(&sDest[i * 2], szTmp, 2); } return; }
//string实现方法字节流转十六进制字符串 std::string ToHexString(const UCHAR* buf, int len, std::string tok/* = " "*/) { std::string output; char temp[8]; for (int i = 0; i < len; ++i) { sprintf(temp, "%.2x", (UCHAR)buf[i]); output.append(temp); if (i < len -1) { output.append(tok); } } return output; }
//十六进制字符串转换为字节流 void HexStrToByte(const char* source, unsigned char* dest, int sourceLen) { short i; unsigned char highByte, lowByte; for (i = 0; i < sourceLen; i += 2) { highByte = toupper(source[i]); lowByte = toupper(source[i + 1]); if (highByte > 0x39) highByte -= 0x37; else highByte -= 0x30; if (lowByte > 0x39) lowByte -= 0x37; else lowByte -= 0x30; dest[i / 2] = (highByte << 4) | lowByte; } return; }
相关文章推荐
- C++模板类函数的使用以及如何使用时间作为文件名保存文件
- 一些可以使你感兴趣的c语言简单练习
- 实验c++2-1(上机报告)
- 文档处理之去停止词和IF-IDF
- C++ Primer读书笔记-ch01
- C++错误输入的处理--整型错误输入字符串
- C语言中的内存分配
- C++大话设计模式之简单工厂模式
- C++库常用函数一览
- C语言编程练习——出现次数最多的数
- C++杂记(1)
- 1019_计算二叉树的高度和结点数
- 贪心算法 田忌赛马(problem C)
- [C++]class内的方法指针
- c++ 继承(详细)
- 01背包算法 动态规划(c++实现)
- c++ 笔记explicit
- C++ 第二次上机实验报告
- C/C++ 获取文件夹下的所有文件列表
- C/C++ 获取文件夹下的所有文件列表