We help IT Professionals succeed at work.

char to asciiHEX in C

chrislock
chrislock asked
on
256 Views
Last Modified: 2011-09-20
a=254; // unsigned char
b=1;  // unsigned char
//UART_Buffer is unsigned char

sprintf(UART_Buffer+1,"%02X",a); // gives 'FE' in [1] and [2]
sprintf(UART_Buffer+3,"%02X",b); // gives '10' in [3] and [4] - WHY NOT '01' ????


Am I being silly?
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2009
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Hamed ZaghaghiMachine Learning Engineer
CERTIFIED EXPERT

Commented:
i use this one and works correct.

unsigned char UART_Buffer[20]={0};
unsigned char a=254; // unsigned char
unsigned char b=1;  // unsigned char
//UART_Buffer is unsigned char
 
sprintf((char*)UART_Buffer+1,"%02X",a); // gives 'FE' in [1] and [2]
sprintf((char*)UART_Buffer+3,"%02X",b); // gives '10' in [3] and [4] - WHY NOT '01' ????

Open in new window

evilrixSenior Software Engineer (Avast)
CERTIFIED EXPERT

Commented:
If your code is going to be C++ then using a stream is a safer way to do this conversion: -
#include <iostream>
#include <sstream>
#include <iomanip>
 
int main()
{
	// Bytes to add to stream
	unsigned char a=0xFF;
	unsigned char b=0x01;
 
	// Stream to convert bytes to hex representation
	std::stringstream UART_Buffer;
 
	// Stream the bytes and convert
	UART_Buffer << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(a);
	UART_Buffer << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(b);
 
	// Output converted bytes
	std::cout << UART_Buffer.str();
}

Open in new window

Author

Commented:
Thanks - it now works fine
CERTIFIED EXPERT
Top Expert 2009

Commented:
I notice that you gave a B grade ... That usually means there was something missing in the answer. Is something still unclear ? If so, feel free to ask for clarification !

Author

Commented:
thanks all - it works OK, but why do you need to cast a and b to an u int?
CERTIFIED EXPERT
Top Expert 2009

Commented:
>> but why do you need to cast a and b to an u int?

%x expects an unsigned int

Author

Commented:
Pretty obvious really! I thought of that just after I sent the last comment.
Thanks again - at least I've learnt something today!
Chris
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.