1

Is it possible to Convert Int to Hexdecimal without using 'printf'?

Best if the all the value are placed in the variable itself and some sample code with explanation.

8
  • 4
    There is no such thing as converting an int to Hex. An int is an int. You want to display your int as hex by formatting the output. Commented Aug 24, 2011 at 15:22
  • 1
    What do you mean by this? Creating a character string which contains the hex representation of the integer? You're not really converting anything when you call printf - you're just formatting it's output. Commented Aug 24, 2011 at 15:22
  • Yeah! You are right! @itsmatt I don't need print out but I need to convert it! Commented Aug 24, 2011 at 15:27
  • Hint: Think in terms of rightshifting 4 bits at a time. Commented Aug 24, 2011 at 15:28
  • 3
    Would you rather have 0xF4240 dollars or 1000000 dollars? Commented Aug 24, 2011 at 15:36

10 Answers 10

5

The decimal and hexadecimal systems are just ways of expressing the value of the int. In a way "it is already a hexadecimal".

Sign up to request clarification or add additional context in comments.

3 Comments

Not really perfect answer if you need it for encryption
Meaning I need the value to be Hex and not Int
The hexadecimal number system and the decimal number system represent the same integer values, for example 10 in decimal equals 0xA in hexadecimal. You can try it out in a conditional statement, for example if(10 == 0xA){printf("Ten is ten");}.
2

I think you can use itoa in stdlib.h :

char * itoa ( int value, char * str, int base ); or sprintf(str,"%x",value);

The documentation : itoa documentation

6 Comments

I saw your link somehow, it need 'printf' which is not what I need
No, it's just for printing, but the result is in the buffer. You can also use sprintf,it doesn't print, just put the result into a buffer.
sprintf exists in C programming, and it's not printf
I am new to C programming. I will take sometime to think. Why is simple thing in Java so difficult in C!!!!
@Ezylryb : Your problem is unclear, edit your question and add the java code that does what you want. With it, we'll be able to understand what you want.
|
0

Of course it is possible. Just think about how printf itself was originally implemented...

I won't give you a full solution, only hints, based on which you can experiment with the implementation in code:

An 8-bit number can be expressed as 2 hex digits, which contain the higher and lower 4 bits, respectively. To get these bits, you can use the bit-shift (>>) and mask (&) operators.

Once you have a 4-bit value, you can easily map it to the correct hex digit using a sequence of ifs, or (as a more elegant solution) by indexing into a character array.

3 Comments

@Ezylryb, which step above you are stuck with? If you ask a more precise question, you get more precise help.
I write my own function and place in a file but somehow when I view it in Linux, I have 'square','triangle', 'star'...
@Ezylryb, your description is cryptic. Do you mean you save the output of the conversion to a file, and you get strange characters instead of the expected hex digits?
0

Hexdecival vs Decimal vs Binary..etc.. are only different bases that represent the same number. printf doesn't convert your number, it generates an hexdecimal string representation of your number. If you want to implement your own study how to make a conversion between decimal and hexdecimal bases.

Comments

0

Yes, it is definitely possible to convert an integer to a hexadecimal string without using the "printf" family of formatting functions.

You can write such a function by converting the number from base-10 (as we think about it) to base-16 (hexadecimal) and printing the digits in that representation (0-9A-F). This will require you to think a lot about the bases we use to represent numbers.

1 Comment

I tried but I have 'square' showing up on my screen when I print into a file
0

If you are referring to displaying an int as a hexadecimal number in C, than you will have to write a function that does the same thing as printf.

If you are referring to casting or internal representation, it can't be done because hexadecimal is not a data type.

Comments

0

An int is stored in your computer as a binary number. In fact, since hex can be interpreted as a shorthand for writing binary, you might even say that when you print out a decimal number using printf, it has to be converted from hex to decimal.

Comments

0

it's an example for convert a char array to hex string format

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

unsigned char d=255;
char hex_array[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char *array_to_hex_string(uint8_t data[],int size);
char test_data[3] = {'0',188,255};
int main()
{

    printf("%s",array_to_hex_string(test_data,3));
    return 0;
 }

 char *array_to_hex_string(uint8_t data[],int size){
 int i,j;
 char *hex_string = (char *)malloc((2*size) * sizeof(data[0]));
for(i=0;i<size;i++){
    hex_string[j] = hex_array[(data[i]>>4)];
    hex_string[j+1] =  hex_array[(data[i] & 15)];

    j +=2;
        }
return (char *)hex_string;
}

Comments

-1
int Convert2Hex(int i){

         
int c =0;int y, z; double a,x,b, fractpart, intpart;        char nc[10]= {'0','1','2','3','4',
                                                              '5','6','7','8','9'};         
                                                    char hc[6]= {'A','B','C','D','E','F'};
char tmp;                           //holds the value in the array
char result[20];                        //string to hold first directional 
char result2[20];                       //string to hold second directional
        
            
            



                
               
intpart = 1;                        //intitialize intpart

double d= 16;

x=i;                            //pass function argument to local variable
        
        
while (intpart != 0) {                  //while the quotiont of the equation 
                                    //isnt 0, keep on dividiing
                
                
a = x / d;      //divide the integer by 16 a,x,d all 
                                        //habe to be doubles
                            


                        
fractpart = modf (a, &intpart);      //from the fractoral
                 
b = (fractpart * 16);       //multiply by 16 to get hex value
                

y = (int) b;               //convert b double into int y
                 
if (y <= 9) { 
         result[c] = nc[y];         //if block handles 0-9 hex
        }
                     
                     
if (y>9){ 
    z = b - 9;             //block handles A-F hex
    result[c]= hc[z-1]; 
    }
                        
                                             
c++;        //increment the index count
                           
x = intpart;    //set the integral to be the next number chunk
                            
                         


                                 }
                     
            

//REVERSE THE ARRAY
int w, f;
f=c-1;

for (w = 0; w <= c;w++) {
                    
            result2[w] = result[f];
            f--; 
            }   
        
result2[c+1] = '\0';
        
printf("0x%s\n", result2);

                                        
}

Comments

-3
cout << hex << intvar << endl;

But if you want an answer that gives you an A for your homework, you're not going to get lucky :)

1 Comment

Possible to have some simple explanation as I have tried out some method but the sample are not as easy as your code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.