C language method of converting 16 binary numbers to strings (improved)

Source: Internet
Author: User

Yesterday wrote a method, can be embedded C commonly used uint8_t data converted to a character, but the program has a warning, embarrassing attack is very uncomfortable, so in today solve the problem. Yesterday's Blog
Char in C is a byte, or 8 bits, that can be represented as a number of 2 16 binary. But the first bit is the sign bit, and the microcontroller uses the C language often does not involve negative numbers, so more common is to use unsigned char (unsigned char), and then defined as uint8_t (typedef unsigned char uint8_t;), This can be expressed in 8 bits as 2 16 binary number, such as 1111 1110 is 0xFE, if you need not 16 binary number, but a character, then you can use the following method to implement the 16 binary to character.

#include <stdio.h>#include <stdlib.h>typedef unsigned Charuint8_t;CharHextoch (uint8_t old); uint8_t Hextochar (uint8_t temp);intMain () {inti =0; uint8_t data[5]={0x12,0x34,0x56,0xAB,0xEF}; uint8_t str[Ten]; uint8_t dst[Ten]; for(i =0; i<5; i++) {str[2*i] = data[i]>>4; str[2*i+1] = data[i]&0xf; } for(i =0; i<Ten; i++) {Dst[i] = Hextochar (Str[i]); } for(i =0; i<Ten; i++) {printf("%c\n", Dst[i]); }return 0;} uint8_t Hextochar (uint8_t temp) {uint8_t DST;if(Temp <Ten) {DST = temp +' 0 '; }Else{DST = temp-Ten+' A '; }returnDST;}

Note that the Hextochar function, because the incoming parameters are unsigned, it is not necessary to determine the positive or negative.
Characters that require lowercase can be modified here DST = temp-10 + ' a ';
Run results

C language method of converting 16 binary numbers to strings (improved)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.