How to convert string to hexadecimal value?(using user-defined functions)

Showing Answers 1 - 2 of 2 Answers

Preetham

  • Sep 26th, 2006
 

Use %x as format specifier while printing, the characters of string, u will get the result in hexadecimal

  Was this answer useful?  Yes

Swati

  • Jan 8th, 2007
 

bool StrtoHex(const char* str)

{

//If string is empty

if(str == NULL)

return false;

//Variable to indicate number is positive or negative. Default is positive

bool isNeg = false;

//Index of string

int index = 0;

int num = 0;

//If first char is '-' then number is negative

if(str[0] == '-')

{

isNeg = true;

index++;

}

while(str[index])

{

//If string is between 0 to 9;

num *=16;

if((str[index] >= '0') && (str[index] <='9'))

{

num = num + str[index] - '0';

}

else if((str[index] >= 'A') && (str[index] <='F'))

{

num = num + str[index] - 'A' + 10;

}

else if((str[index] >= 'a') && (str[index] <='f'))

{

num = num + str[index] - 'a'+ 10;

}

else

{

printf("Wrong String");

return false;

}

index++;

}

if(isNeg)

{

printf("-");

}

printf("%X",num);

return true;

}

  

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions