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

Thursday, August 11, 2022

[FIXED] How to convert from Hex to Decimal using only Integers in C

 August 11, 2022     c, decimal, hex     No comments   

Issue

I'm receiving the following data over a serial port: <0x1b><0x2e><0x15>...
Each value enclosed in '<>' is a single byte.
I require the third byte from the data so i do this:

int Length;
char Data[..];
Length = Data[2];

But the value of Length is 21 and not 15 because the value written in memory is hex. How do i convert the decimal representation of 15 to decimal 15?

I've tried converting it to various types and so on.. But none of that works for me as i'm writing a driver and performance matters a lot. I've looked over stackoverflow and other sites but all the given examples are with strings, none are with plain integers.

When i send it to the rest of the algorithm i run into issues as the algorithm expects 15.


Solution

Given int x that contains 8 bits that represent a number using natural packed binary-coded decimal, they can be converted to the number with:

int y = x/16*10 + x%16;

x/16 produces the high four bits, and then multiplying by ten scales them to the tens position. x%16 produces the low four bits. They are kept in the ones position and added to the tens.



Answered By - Eric Postpischil
Answer Checked By - David Marino (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

1,214,421

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 © 2025 PHPFixing