zoukankan      html  css  js  c++  java
  • C语言 字节数组和hex和互相转换

    C语言 字节数组和hex和互相转换

    #include<iostream>
    #include<string.h>
    #include<stdio.h>
    
    //字节流转换为十六进制字符串
    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 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;
    }
    
    
    int main()
    {
    	char array[5] = { 12,45,-12,34,32 };
    	char out[1024] = { 0 };
    	char arrayout[1024] = { 0 };
    	ByteToHexStr((const unsigned char*)array, out, 5);
        printf("%s
    ",out);
    	HexStrToByte((const char*)out, (unsigned char*)arrayout, strlen(out));
        printf("{");
        for(int i = 0; i<strlen(arrayout);i++)
        {
            printf("%d ",arrayout[i]);
        }
        printf("}");
    }
    

      

  • 相关阅读:
    「CSP-S 2019」初赛解析
    「SP741」STEAD
    「CF1382B」Sequential Nim
    「二分图」学习笔记
    题解 P3321 【[SDOI2015]序列统计】
    题解 P5339 【[TJOI2019]唱、跳、rap和篮球】
    题解 P3200 【[HNOI2009]有趣的数列】
    题解 P2606 【[ZJOI2010]排列计数】
    题解 CF1095F 【Make It Connected】
    题解 CF1155E 【Guess the Root】
  • 原文地址:https://www.cnblogs.com/wuyepeng/p/13174224.html
Copyright © 2011-2022 走看看