Ammar
Ammar

Reputation: 1233

How to Convert ASCII into Byte?

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!

Upvotes: 2

Views: 2492

Answers (3)

zmo
zmo

Reputation: 24812

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

Upvotes: 1

TerraOrbis
TerraOrbis

Reputation: 91

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];

Upvotes: 1

M.M
M.M

Reputation: 141554

This is called BCD (binary-coded decimal).

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

Upvotes: 4

Related Questions