Recently, when I was working on a project, I encountered encryption, decryption, and encapsulation of the Protocol. Among them, I often encountered the conversion between unsigned data and common data types. So after research, I have encapsulated several functions and shared them here. I hope you can correct them if you have any shortcomings.
Unsigned short unchartounshort (unsigned char * pbuf)
{
Unsigned short result = 0;
Result = (short) pbuf [0] * 256;
Result + = (short) pbuf [1];
Return result;
}
Unsigned int unchartounint (unsigned char * pbuf)
{
Unsigned int result = 0;
Result = (short) pbuf [0] * 256*256*256;
Result + = (short) pbuf [1] * 256*256;
Result + = (short) pbuf [2] * 256;
Result + = (short) pbuf [3];
Return result;
}
The preceding two functions convert unsigned char * to unsigned short or unsigned Int. The data is stored in the first byte and the lower byte, for example, the unsigned short integer 256 is 0x01 0x00. We get the low position data in turn and multiply it by 0xff to get the integer value represented by the low position, and then add the values of each bit to get the final unsigned integer value. Convert a byte to the short type to obtain the unsigned integer value of the byte. Because a short value occupies two characters, we can convert it like this, in fact, only the short high byte is used.
Void unsigtounchar (unsigned char * pbuf, unsigned short ivalue)
{
Pbuf [0] = (unsigned char) (ivalue> 8 );
Pbuf [1] = (unsigned char) (ivalue );
}
Void uninttounchar (unsigned char * pbuf, unsigned int ivalue)
{
Pbuf [0] = (unsigned char) (ivalue> 24 );
Pbuf [1] = (unsigned char) (ivalue> 16 );
Pbuf [2] = (unsigned char) (ivalue> 8 );
Pbuf [3] = (unsigned char) (ivalue );
}
The above two functions are used to convert the unsigned integer to the unsigned char type. The method used is to shift the integer value to a multiple of 8 to the right, convert it from a strong position to an unsigned char, and assign the value to each byte in the unsigned char array.
There are many ways to convert the unsigned data type and the signed data type. Here, I think it is simple and easy to understand. The Code has been tested in Vs and Linux. If you have a better way, please contact us. I will update this article to help other colleagues learn more.