Problem link = https://www.naukri.com/code360/problems/convert-to-hexadecimal_1102544
My solution is following
string toHex(int num) {
string ans = "";
// Loop through the integer in 4-bit chunks
for (int i = 28; i >= 0; i -= 4)
{
// Lines of conflict
/***********************************************/
// Extract 4 bits starting from bit position i
int number_before = (num & (15 << i));
number_before = (number_before >> i) ;
/***********************************************/
// Convert to hexadecimal character and append to result string
if(number_before == 0 && ans.size() == 0) continue;
else if (number_before < 10) {
ans += (char)(number_before + '0'); // Convert 0-9 to '0'-'9'
} else {
ans += (char)(number_before - 10 + 'A'); // Convert 10-15 to 'A'-'F'
}
}
return ans;
}
int number_before = (num & (15 << i));
number_before = (number_before >> i) ;
int number_before = ((num>> i) & 15 );
Two statements are provided in above question as mentioned above.
In this problem i try to record group of 4 bits at once in number “number_before” from number “num”. “num” can be positive & negative. Second statement is working correctly as expected. But first is producing unexpected results .Can anyone tell the reason why ?
New contributor
Satyam Mittal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.