Convert Int to Hexdecimal without using 'printf' (C Programming) - c

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.

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

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

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.

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.

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.

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.

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.

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;
}

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 :)

Related

Convert string containing binary representation into number - C

I have a binary message on a string. The string contains values such as "10001000" and it's being used as a buffer to store binary representations of different data types. I will parse the data and then convert each sequence. My struggle is to convert an specific string of 1s and 0s into: integer, float or double. A possible solution for the int is strtol, but it doesn't solve all my problem...
I've read throw many discussions of people trying to create a string containing the binary representation of a number. But my issue is exactly the opposite: roll back the number once I have a string with it's binary representation.
Any thoughts or advices will be most welcome.
This is quite simple really...
unsigned int number;
char str[33];
int i;
int s;
/* Read some 32-bit binary number in character representation in str. */
Do some stuff.
/* Convert from string to binary. */
number = 0;
s = strlen(str);
for (i = 0; i < s; i++)
{
if (str[i] == 0x00) break;
if (str[i] == '0')
{
number |= 1;
number << 1;
}
if (str[i] == '1')
{
number &= 0xFFFFFFFE;
number << 1;
}
}
Generally, you can find this on Google or in your textbook. So you got this for free, this time.
EDIT:
I noticed that you also mentioned float or double as well. Those are complicated data types that are defined by the IEEE-754 standard. If the binary string is already in floating point representation, then you can just use a union to get from an unsigned int to one of the float types. Code below:
union float_conversion_t
{
unsigned int i[2];
float f;
double d;
};
Here you datafill one or both integers and then read the float or double value. You may need to adjust the size of the array depending on the word size of your machine (32-bit, 64-bit, or something else).
Thank you to Daniel and all other valid comments.
The main question was if float/double conversions were possible with any preexisting function. My understanding after all this (correct me plz if I'm wrong) is no.
So one must go trough the math and conversion for floating points (lots of documentation on IEEE 754 online...) and use strtol for integers. Fair enough.
It may be of help to others:
Here's a conversion of binary IEEE 754 as string to double
But if you look for converting something like "1001.1101" (binary point representation) to float, this guy did a nice job

Converting from long to hex in C?

I have this code
char binary[] = "0001001010000011";
long number = strtol(binary, NULL, 16);
printf("%x", number);
I want to convert the string into a hex number. the answer is 1283, but i am getting DF023BCF what am i doing wrong?
The base you specify to strtol is the base to use to parse the input, not the output (which instead is specified by the %x). IOW, that code says to strtol to parse 0001001010000011 as if it were a hexadecimal number (and, by the way, it results in overflow).
The last parameter to strtol is the base that you want to convert from. Since you are providing a binary encoded string you should specify a base 2 conversion.
Here is the correct code:
char binary[] = "0001001010000011";
long number = strtol(binary, NULL, 2);
printf("%x", number);
I would also suggest that binary numbers are not normally signed (especially when 17 digits long), therefore, it seems likely that you may want to use the unsigned version of the function, strtoul() as shown below. Finally, when printf'ing a number into hex format it might be a good idea to indicate hexadecimal with a leading 0x marker. In your case, the answer is 0x1283 but displaying this number as 1283 allows it to be easily confused as a decimal number. Both suggestions are shown below.
const char binary[] = "0001001010000011";
unsigned long number = strtoul(binary, NULL, 2);
printf("0x%x", number);

I can't print the results of bitwise operators [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can I use a binary literal in C or C++?
I cannot display the results of bitwise operators in C. In the code below, a&b should be 100001 and a|b 111111. However, the printed results are different. I tried to do this with and without itoa, but to no avail. Why doesn't the program print the answers correctly?
#include<stdio.h>
#include<stdlib.h>
int main (int argc, char* argv[]) {
unsigned a = 101101;
unsigned b = 110011;
unsigned c = a&b;
unsigned d = a|b;
char s[100];
char t[100];
itoa(c,s,2);
itoa(d,t,2);
printf("%s\n",s); /* Shouldn't it produce 100001?
Instead I get 11000100010101001*/
printf("%s\n",t); /* Ought to print 111111.
Instead it prints 11010111111111111 */
return 0;
}
Thank You
The numbers you provide are decimal, while you meant to use binary. Try the following:
unsigned a = 0x2d; // 101101 b
unsigned b = 0x33; // 110011 b
Or for a GCC compiler use:
unsigned a = 0b101101;
unsigned b = 0b110011;
You need to express your numbers as decimal (e.g. 101101 becomes 45, 110011 becomes 51), ocatal (101101 becomes 055, 110011 is 063) or hexadecimal (as Eli shows, 0x2d and 0x33 respectively).
Some compilers MAY support binary, but most don't. Working directly in binary is painful anyways once numbers get more than about 8-12 bits long, so learning how to work with binary in either hex (most common these days) or octal (used to be popular in the 1970's, particularly on DEC equipment that used a lot of 3-bit combinations, so it made sense).
You could of course use strtol(str, NULL, 2) to translate a binary string to a long value.
The integers you have defined (a and b) are not defined using bits. You have defined integers that are 101101 and 110011. So even with proper display, that would not work.
What I recommend you to get more or less what you want is:
First properly define your number. Some C compilers (as far as I know, this is not standard) define the bit notation, so a would be: 0b101101 and b would b: 0b110011. That way:
unsigned a = 0b101101;
unsigned b = 0b110011;
Otherwise, you have to either define them using hexadecimal notation (0x....) or directly in 10-base. In first case, a would be: 0x2d or 45.
Furthermore, for the display, you have no way to display bits. So, you should to display with hexadecimal notation (which is more appropriate for that kind of things), using: printf("c: %#x", c);
It will output: c: 0x21.

Convert a string of hexadecimal digits into integer

I am trying to implement the htoi(s) [Dennis Ritchie chapter2 exercise 2-3 Q] which converts a string of hexadecimal digits, into its equivalent integer, can anyone help me out in the logic of this program, i dont need the code, i just need the logic for implementing it. I am not able to get the correct logic
Let's take a step back:
How would you implement a function that accepts a single hex digit and returns it's decimal equivalent?
In other words, how would you write this function:
unsigned int hextodec(char c)
{
... your code here
}
Hint: for decimal digits what happens when you calculate c -'0'?
Once you have this function it should be fairly easy to use it to calculate the conversion of longer hex strings.
Hint: 0xF is 15 and 0x10 is 16
Use the strtol function with base 16.
About this way:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int xstrtol16(const char *s)
{
errno = 0;
char *endp = NULL;
int result = strtol(s, &endp, 16);
if (*charp || errno) {
fprintf(stderr, "Failed to convert...\n");
exit(1);
}
return result;
}
Think about what a printable number (in any base) is. Basically a list of symbols which represent simple numeric values (0...base-1), and associated "weights" of their digit positions. For decimal the symbols are "0123456789" and the weights are 1, 10 , 100, 1000...
You convert the printable number into "integer" by finding the corresponding numeric value of each symbol, multiplying it times the weight for that digit position, and summing those products together. There are tricks to doing this efficiently, but a straight-forward "dumb" implementation can get the job done perfectly well.
Hex is slightly complicated because there are two runs of symbols -- 0-9 and A-F -- and it's sometimes desired to accept both upper-case and lower-case letters. There are again tricks to handling this, but doing it in a straight-forward fashion (compare each character to the limits of each run and decide which one it fits) is perfectly fine (and more general than other approaches). You can also even use a index op, where you simply find the character's index into "0123456789ABCDEF" -- inefficient but simple.

C convert hex to decimal format

Compiling on linux using gcc.
I would like to convert this to hex. 10 which would be a.
I have managed to do this will the code below.
unsigned int index = 10;
char index_buff[5] = {0};
sprintf(index_buff, "0x%x", index);
data_t.un32Index = port_buff;
However, the problem is that I need to assign it to a structure
and the element I need to assign to is an unsigned int type.
This works however:
data_t.un32index = 0xa;
However, my sample code doesn't work as it thinks I am trying to convert
from an string to a unsigned int.
I have tried this, but this also failed
data_t.un32index = (unsigned int) *index_buff;
Many thanks for any advice,
Huh? The decimal/hex doesn't matter if you have the value in a variable. Just do
data_t.un32index = index;
Decimal and hex are just notation when printing numbers so humans can read them.
For a C (or C++, or Java, or any of a number of languages where these types are "primitives" with semantics closely matching those of machine registers) integer variable, the value it holds can never be said to "be in hex".
The value is held in binary (in all typical modern electronic computers, which are digital and binary in nature) in the memory or register backing the variable, and you can then generate various string representations, which is when you need to pick a base to use.
I agree with the previous answers, but I thought I'd share code that actually converts a hex string to an unsigned integer just to show how it's done:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *hex_value_string = "deadbeef";
unsigned int out;
sscanf(hex_value_string, "%x", &out);
printf("%o %o\n", out, 0xdeadbeef);
printf("%x %x\n", out, 0xdeadbeef);
return 0;
}
Gives this when executed:
emil#lanfear /home/emil/dev $ ./hex
33653337357 33653337357
deadbeef deadbeef
However, my sample code doesn't work as it thinks I am trying to convert from an string to a unsigned int.
This is because when you write the following:
data_t.un32index = index_buff;
you do have a type mismatch. You are trying to assign a character array index_buff to an unsigned int i.e. data_t.un32index.
You should be able to assign the index as suggested directly to data_t.un32index.

Resources