Page 49

Write a function invert(x,p,n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others unchanged.

#include <stdio.h>
#include <ctype.h>

int htoi(char s[]);

int main()
{
	char input[] = "0x123";

	printf("Result: %d\n", htoi(input));
}

int htoi(char s[])
{
	int i = 0;
	int result = 0;
	char c;

	if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
		i = 2;
	}

	for (; (c = s[i]) != '\0'; i++) {
		result *= 16;
		if (isdigit(c)) {
			result += (c - '0');
		} else if (c >= 'a' && c <= 'f') {
			result += (c - 'a') + 10;
		}
	}

	return result;
}