Ask your own question, for FREE!
Computer Science 21 Online
OpenStudy (anonymous):

how to convert the hexdecimal to octal using loop

OpenStudy (anonymous):

plz any one tell me

OpenStudy (anonymous):

Have a look at http://openstudy.com/users/slotema#/updates/51043c1ae4b0ad57a5631116 It describes converting decimal to hexadecmal, but will also work for converting hexadecimal to octal by first converting the hexadecimal to decimal (yes, you can do it directly, but it's a bit more complicated)

OpenStudy (anonymous):

#include <stdio.h> #include <string.h> #include <stdlib.h> int get_val(char hex_digit) { if (hex_digit >= '0' && hex_digit <= '9') { return hex_digit - '0'; } else { return hex_digit - 'A' + 10; } } void convert_to_oct(const char* hex, char** res) { int hex_len = strlen(hex); int oct_len = (hex_len/3) * 4; int i; // One hex digit left that is 4 bits or 2 oct digits. if (hex_len%3 == 1) { oct_len += 2; } else if (hex_len%3 == 2) { // 2 hex digits map to 3 oct digits oct_len += 3; } (*res) = malloc((oct_len+1) * sizeof(char)); (*res)[oct_len] = 0; // don't forget the terminating char. int oct_index = oct_len - 1; // position we are changing in the oct representation. for (i = hex_len - 1; i - 3 >= 0; i -= 3) { (*res)[oct_index] = get_val(hex[i]) % 8 + '0'; (*res)[oct_index - 1] = (get_val(hex[i])/8+ (get_val(hex[i-1])%4) * 2) + '0'; (*res)[oct_index - 2] = get_val(hex[i-1])/4 + (get_val(hex[i-2])%2)*4 + '0'; (*res)[oct_index - 3] = get_val(hex[i-2])/2 + '0'; oct_index -= 4; } // if hex_len is not divisible by 4 we have to take care of the extra digits: if (hex_len%3 == 1) { (*res)[oct_index] = get_val(hex[0])%8 + '0'; (*res)[oct_index - 1] = get_val(hex[0])/8 + '0'; } else if (hex_len%3 == 2) { (*res)[oct_index] = get_val(hex[1])%8 + '0'; (*res)[oct_index - 1] = get_val(hex[1])/8 + (get_val(hex[0])%4)*4 + '0'; (*res)[oct_index - 2] = get_val(hex[0])/4 + '0'; } }

OpenStudy (rsmith6559):

Converting numbers from one base to another is usually done recursively.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!