Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

octal character to integer/byte conversion - please help

Status
Not open for further replies.

nappaji

Programmer
Mar 21, 2001
76
US
If I have an octal character constant say, \377 which in binary is 11111111 (8 one's). This is a single byte. How do I convert it into an integer ??? I have to be able to read individual bits..

The problem is that \377 is accessible as a single character and I donot know how to access the individual bits.

Please help.
 
hey! do it like

int x=1;
int y=\377
char bit;
do{
bit = y&1<<x;
bit=>>x;
/////here u'll get that bit

}
while(x!=8)

 
x was not incremented

you can also do this and start with 7 so the output is correct because your outputting from highest to lowest. With the 377, you will see the correct end result but it is actually in reverse.

for(int i = 7;i<=0;i++)
{
int bit = value & 1<<i;
printf(&quot;%d&quot;,bit);
}

if you are reading the value into a string and are trying to convert it to a decimal

char strVal[] = &quot;377&quot;;
char* endPtr;
int value = strtol(strVal,endPtr,8);

Matt
 
another solution , use union:

union BitsType{
char aNum;
struct Bits{
unsigned short b1:1;
unsigned short b2:1;
unsigned short b3:1;
unsigned short b4:1;
unsigned short b5:1;
unsigned short b6:1;
unsigned short b7:1;
unsigned short b8:1;
} Bits;
};

void main ()

{
BitsType test ;
test.aNum = 0x86;
int b1 = test.Bits.b1;
int b2 = test.Bits.b2;
int b3 = test.Bits.b3;
int b4 = test.Bits.b4;
int b5 = test.Bits.b5;
int b6 = test.Bits.b6;
int b7 = test.Bits.b7;
int b8 = test.Bits.b8;
}
 
'\377' already is an integer, it's just expressed in octal notation. Here are some macros for testing,setting and clearing a bit:

/* Evaluates to 1 if bit B in N is set, 0 if not. */
#define TEST_BIT(N,B) (!!((N) & 1U<<(B)))
/* Sets bit B in N */
#define SET_BIT(N,B) ((N)|=(1U<<(B)))
/* Clears bit B in N */
#define CLEAR_BIT(N,B) ((N) &= ~(1U<<(B)))

To print all the bits of a number:

void print_bits(unsigned n)
{
int i;
for (i=0;i<(sizeof n * CHAR_BIT);++i) {
printf(&quot;BIT %d=%d\n&quot;,i,TEST_BIT(n,i));
}
}

BTW, though Jeffray's solution with unions might often work, it's not portable because accessing a different union member than the one last written to invokes undefined behavior.
Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top