Question

For example if I received the following ASCII value: 123456

How would I combine two digits into a byte? So my bytes become like this ...

byte1 = 0x12;

byte2 = 0x34;

byte3 = 0x56; 

Thanks!

Était-ce utile?

La solution 2

well here's a way to do it:

char string[] = "123456";
int byte1 = (string[0]-'0')*0x10 + (string[1]-'0');
int byte2 = (string[2]-'0')*0x10 + (string[3]-'0');
int byte3 = (string[4]-'0')*0x10 + (string[5]-'0');

HTH

Autres conseils

This is called BCD (binary-coded decimal).

char s[] = "123456";
byte1 = (s[0] - '0') * 0x10 + (s[1] - '0');

I figured I'd elaborate on my comment. I'd just have some bitwise fun.

char string[] = "123456"
byte1 = ((unsigned char)string[0] << 4) | (unsigned char)string[1];
byte2 = ((unsigned char)string[2] << 4) | (unsigned char)string[3];
byte3 = ((unsigned char)string[4] << 4) | (unsigned char)string[5];
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top