fork(13) download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. int get_val(char hex_digit) {
  5. if (hex_digit >= '0' && hex_digit <= '9') {
  6. return hex_digit - '0';
  7. } else {
  8. return hex_digit - 'A' + 10;
  9. }
  10. }
  11. void convert_to_oct(const char* hex, char** res) {
  12. int hex_len = strlen(hex);
  13. int oct_len = (hex_len/3) * 4;
  14. int i;
  15.  
  16. // One hex digit left that is 4 bits or 2 oct digits.
  17. if (hex_len%3 == 1) {
  18. oct_len += 2;
  19. } else if (hex_len%3 == 2) { // 2 hex digits map to 3 oct digits
  20. oct_len += 3;
  21. }
  22.  
  23. (*res) = malloc((oct_len+1) * sizeof(char));
  24. (*res)[oct_len] = 0; // don't forget the terminating char.
  25.  
  26. int oct_index = oct_len - 1; // position we are changing in the oct representation.
  27. for (i = hex_len - 1; i - 3 >= 0; i -= 3) {
  28. (*res)[oct_index] = get_val(hex[i]) % 8 + '0';
  29. (*res)[oct_index - 1] = (get_val(hex[i])/8+ (get_val(hex[i-1])%4) * 2) + '0';
  30. (*res)[oct_index - 2] = get_val(hex[i-1])/4 + (get_val(hex[i-2])%2)*4 + '0';
  31. (*res)[oct_index - 3] = get_val(hex[i-2])/2 + '0';
  32. oct_index -= 4;
  33. }
  34.  
  35. // if hex_len is not divisible by 4 we have to take care of the extra digits:
  36. if (hex_len%3 == 1) {
  37. (*res)[oct_index] = get_val(hex[0])%8 + '0';
  38. (*res)[oct_index - 1] = get_val(hex[0])/8 + '0';
  39. } else if (hex_len%3 == 2) {
  40. (*res)[oct_index] = get_val(hex[1])%8 + '0';
  41. (*res)[oct_index - 1] = get_val(hex[1])/8 + (get_val(hex[0])%4)*4 + '0';
  42. (*res)[oct_index - 2] = get_val(hex[0])/4 + '0';
  43. }
  44. }
  45.  
  46. int main() {
  47. const char* hex_val = "A111";
  48. char * res;
  49. convert_to_oct(hex_val, &res);
  50. printf("%s", res);
  51. free(res);
  52. return 0;
  53. }
Success #stdin #stdout 0.01s 1852KB
stdin
Standard input is empty
stdout
120421