Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 2 char into 1 int [closed]

Tags:

c

casting

char

int

I have 2 chars: HIGH and LOW and I'd like to convert them to an int corresponding to HIGH + the 2 left bits from LOW.

I tried somethine like :

unsigned char high;
unsigned char low;
high = 128; // 10000000
low= 128; // 10000000
int result; (should be high 10000000 + 2 left bites of low 10 = 1000000010)
// To do
return result;

Edited for more clarity.

The solution I chosed is:

return high*4 + (low >> (CHAR_BIT - 2));
like image 675
Leo Avatar asked Dec 15 '12 16:12

Leo


2 Answers

You declare HIGH and LOW as char*, but you don't use them as pointer. The following code works fine (BTW, avoid upper case identifiers when you don't use constants):

char high = 125;
char low = 12;

This is how I understand your question (it could be more understandable):

#include <limits.h>

int result = high + (low >> (CHAR_BIT - 2));
like image 151
md5 Avatar answered Sep 21 '22 02:09

md5


I have 2 chars, HIGH and LOW, and I'd like to convert them to an int corresponding to HIGH + the 2 left bits from LOW.

Your specification is not clear. Given:

unsigned char HIGH = 152;
unsigned char LOW  =  12;

It could mean:

int result = HIGH + (LOW >> 6);   // Assuming CHAR_BIT == 8

Or it could mean:

int result = HIGH + (LOW & 0xC0);

Or it could mean:

int result = (HIGH << 2) | (LOW >> 6);

Or it could have some other meaning. For the values shown in the question, the first two expressions produce the same answer.

To get a more meaningful answer, you'll have to spell out the requirements much more carefully. Your actual code bears almost no discernible relationship to the requirement you specify. You have two char * variables; you initialize them to what are almost certainly invalid addresses; you don't initialize result. Your computations are, at best, odd.

like image 28
Jonathan Leffler Avatar answered Sep 23 '22 02:09

Jonathan Leffler