Hi guys,

I need to write a piece of code which takes two strings (char arrays) containing hex values and perform an AND operation on them. (The aim is to mask bits from the first value). A Mask value of all Fs means that we don't want to mask any bits.

E.g., for these values:

| MemoryAddress | Mask |
------------------------
| 1006 | FFFF |

I would need to simply read the memory address 1006.

For these values:

| MemoryAddress | Mask |
------------------------
| 1006 | FFF0 |

I would need to read memory address 1000.

Really what I think I need to do is to first convert the hex into binary, then perform the AND operation, then convert that back to hex. Any suggestions as to how this could be implemented quickly and easily?

I have made a start with the code below, but it's not going to work because it's converting each char individually, which is of no use to me (1006 in hex is represented as (1 x(16x4)) + (0 x(16x3)) + (0 x(16x2)) + (6 x(16x1)

int TSL1_Convert(char inputData)
/*******************************************************************************

	Name:		TSL1_Convert
					
	Description:	Converts the input char from hex to dec as int 
	Inputs:         inputData:  The char to be converted

	Outputs:        
*******************************************************************************/
{
	iErrorCode = 0;
	int i;
	const char *hexDigits = "0123456789ABCDEF";

	for (i = 0; hexDigits[i] != '\0'; i++)
	{		
		if (toupper ((unsigned char)inputData) == hexDigits[i])
		{
			iErrorCode = 0;
			break;
		}
		else 
			iErrorCode = -108;	// Invalid value in hex string
	}

	return hexDigits[i] != '\0' ? i : -1;	
}


unsigned TSL1_htoi (const char *s)
/*******************************************************************************

	Name:		TSL1_htoi
					
	Description:	Converts the input string from hex to dec as int 
	Inputs:         *s:  The string to be converted

	Outputs:        
*******************************************************************************/
{
	unsigned result = 0;

	while ( *s != '\0' )
	{
		result = TSL1_Convert(*s++);
		if (result != -108)
			result = 16 * result;
	}
	return result;
}

Any help appreciated.

Recommended Answers

All 2 Replies

int num1, num2;
std::cin>>std::hex>>num1;
std::cin>>std::hex>>num2;
int result = num1 & num2;
std::cout<<std::hex<<result;

Sorry I should have mentioned that I can only use standard (ANSI C) library functions in the solution.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.