PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

[FIXED] How to convert these hex values to decimal in C

 August 10, 2022     c, decimal, hex     No comments   

Issue

I have a text file in C containing hex values in this format:

   F4 C3 56 78 A3

I want to store the decimal equivalents of these hex numbers into an unsigned char* array.

I know how to load the hex values into the array, but not how to convert them to decimal.

How can I do this?

Thanks


Solution

A mix with sscanf et prinf can do the job.

#include <stdio.h>

bool isHexaDigit(char p) {
    return (( '0' <= p && p <= '9' ) || ( 'A' <= p && p <= 'F'));
}

int main(int argc, char** argv) 
{ 
    char t[]="F4 C3 FF 00 78 A3";
    char* p = t;
    char val[3]; // 2 hexa digit 
    val[2] = 0;  //and the final \0 for a string
    int number; 
    
    while (isHexaDigit(*p) && isHexaDigit(*(p+1))) {
            val[0] = *p;
            val[1] = *(p+1);

            sscanf(val,"%X", &number);    // <---- Read hexa string into number
            printf("\nNum=%i",number);    // <---- Display number to decimal.
              
            p++;
            p++;
            if (!*p) break;
            p++;
      }
   return 0; 
} 


Answered By - Florent
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing