Leading zeros in Hexadecimal int variable C - c

I converting binary to HEXA but i need output with leading zeros. I use this number in this function -> creat(outfile, hexa_num); From 011101110111 I will get 777 but i need 0777. Here is my converting function. Any suggestions ?
char bin_final[]="011101110111";
char *a = bin_final;
int hexa_num = 0;
do {
int b = *a=='1'?1:0;
hexa_num = (hexa_num<<1)|b;
a++;
} while (*a);

Easy, just use strtoul() and regular snprintf(), no need to re-invent anything.
const unsigned long number = strtoul("011101110111", NULL, 2);
char buf[16];
snprintf(buf, sizeof buf, "%04lx", number);
puts(buf);
This prints
0777
Of course if you want to always just print it you can collapse the final three lines into just:
printf("%04lx\n", number);

You can use %04d: the 0 means leading Zeros in 4 digits.
e.g.:
printf("%04d", hexanum);
If you want it in an string use sprintf instead of printf. The number (int hexa_num) itself doesn't have leading zeros but you can format it, just as you have your binary number not as a number but as a character string.

Related

Print negative hex with 6 char in C

I try to print a negative number in hex and I want it to be in 6 char.
For example, -132 in hex is ffffff7c and the wanted output should be ffff7c.
For positive number this line work:
fprintf(fd,"%07d \t%06x \n",i+100,instruction_data[i]);
for negative numbers, I get two more f.
Based on the solution provided by #pmg in comments:
#include <stdio.h>
void print_hex (int val, size_t digits)
{
char tmp[100];
size_t length = sprintf(tmp, "%X", (unsigned int)val);
if(digits > length)
{
digits = length;
}
printf("%.*s\n", digits, tmp+length-digits);
}
int main (void)
{
print_hex(-132,6); // FFFF7C
print_hex(-132,3); // F7C
print_hex(-132,666); // FFFFFF7C
print_hex(132,2); // 84
}
Explanation:
The sprintf call converts the passed number to ASCII hex and stores it in a temporary buffer.
The cast to unsigned int is necessary for the %X specifier.
sprintf returns the number of characters written.
if(digits > length) { digits = length; } is some simple error handling to ensure that the function doesn't attempt to print more digits than present.
The %.*s trick in printf allows the first parameter to specify how many characters to write, variably.
tmp+length-digits is pointer arithmetic ensuring to print digits number of characters from the end of the string, rather than from the beginning, which we would have gotten if we just wrote tmp.
To only print 6 hex digits for negative numbers on 32-bit architectures, you can simply mark the value with 0xffffff:
fprintf(fd, "%07d \t%.6x \n", i + 100, instruction_data[i] & 0xffffffU);
To specify the number of digits as an int variable:
int digits = 6;
...
fprintf(fd, "%07d \t%.*x \n", i + 100, digits,
instruction_data[i] & ~(~0U << (digits * 2) << (digits * 2)));

Converting a binary string to integer

When I try and convert my binary string to int I am receiving a couple of mistakes that I can not figure out. First I am reading from a file and the leading zeros are not showing up when I convert and the new line is showing zero.
This code I am using from this questions: Convert binary string to hexadecimal string C
char* binaryString[100];
// convert binary string to integer
int value = (int)strtol(binaryString, NULL, 2);
//output string as int
printf("%i \n",value)
My txt file and what I am expecting as an output:
00000000
000000010001001000111010
00000000000000000000000000000001
101010111100110100110001001001000101
What I get:
0
0
70202
1
-1127017915
This line:
char* binaryString[100];
Is declaring an array of 100 char pointers (or 100 strings). You probably meant this to declare a buffer of 100 characters to be interpreted as a single string:
char binaryString[100];
char *binaryString[100];
// You are creating an array of pointers in this scenario, use char binaryString[100] instead;
int value = (int)strtol(binaryString, NULL, 2);
// 101010111100110100110001001001000101 Is a 36 bit number, int (in most implementations) is 32 bit. use long long (64 bit in visual c++) as type and strtoll as function instead.
printf("%i \n",value)
Must be printf("%lld \n", value).
In summary:
#include "stdio.h"
#include "stdlib.h" // required for strtoll
int main(void)
{
char str[100] = "101010111100110100110001001001000101";
long long val = 0;
val = strtoll(str, NULL, 2);
//output string as int
printf("%lld \n", val);
return 0;
}
if im understanding this correctly you want to take a binary string so ones and zeros and convert it to a Hex string so 0-F, if so the problem is with the Write not the Convert, you specified '%i' as the written value format, what you need to do for hex is specify '%x'
Change this "printf("%i \n",value)" to "printf("%x\n",value)"

C Programming: Convert Hex Int to Char*

My question is how I would go about converting something like:
int i = 0x11111111;
to a character pointer? I tried using the itoa() function but it gave me a floating-point exception.
itoa is non-standard. Stay away.
One possibility is to use sprintf and the proper format specifier for hexa i.e. x and do:
char str[ BIG_ENOUGH + 1 ];
sprintf(str,"%x",value);
However, the problem with this computing the size of the value array. You have to do with some guesses and FAQ 12.21 is a good starting point.
The number of characters required to represent a number in any base b can be approximated by the following formula:
⌈logb(n + 1)⌉
Add a couple more to hold the 0x, if need be, and then your BIG_ENOUGH is ready.
char buffer[20];
Then:
sprintf(buffer, "%x", i);
Or:
itoa(i, buffer, 16);
Character pointer to buffer can be buffer itself (but it is const) or other variable:
char *p = buffer;
Using the sprintf() function to convert an integer to hexadecimal should accomplish your task.
Here is an example:
int i = 0x11111111;
char szHexPrintBuf[10];
int ret_code = 0;
ret_code = sprintf(szHexPrintBuf, "%x", i);
if(0 > ret_code)
{
something-bad-happend();
}
Using the sprintf() function like this -- sprintf(charBuffer, "%x", i);
-- I think will work very well.

Getting a hex value from a "0x4000" (for example) string and storing it in a variable.

Here's my issue:
I have written a function to detect if a string is hex based off of the "0x####" format:
int lc3_hashex(char *str)
{
int val = 0;
char *to;
to = strndup(str+2, 10);
val = sscanf(to, "%x", &val);
if (val)
{
return val;
}
return 0;
}
Assuming the parameter is of the form "0x####", it returns the decimal version of the post "0x" numbers. But is there any built in way (or a way I am just overseeing) to get the integer value of the hexidecimal number "0x4000" as opposed to the integer value of "4000"?
Thanks.
You can reduce that function to:
int cnt = sscanf(str, "%x", &val);
if (cnt == 1) {
// read a valid `0xNNNN` string
}
scanf with the %x format already does the hex conversion, and deals with the 0x prefix just fine. Also, it's return value is the number of items matched, so you can use that to determine if it did find a hex value in str or not.
With this you have both pieces of information you need: whether or not the string was formatted as you expected it, and what value it was (properly converted). It also avoids a string allocation (which you're not freeing), and the bug your code has if strlen(str) is less than two.
If you change your function signature to:
int check_and_get_hex(const char *str, int *val);
(or something like that), update the sscanf call accordingly (passing val rather than &val), and return (cnt == 1), you can get both the "it's a valid hex string" and the value to the caller in a single shot.
Use strtol from stdlib.h and specify the base as 16.
The only downside is that this function returns 0 upon failure, so you'll want to check to make sure the input to it is not 0.
I fail to understand why the string is being cut short before doing sscanf. If you want the string in hex value to be converted to the decimal integer, you can give it directly.
#include<stdio.h>
int main()
{
char sHex[7] = "0x2002";
int nVal = 0;
sscanf( sHex, "%x", &nVal );
printf( "%d", nVal );
return 0;
}
This will print 8194, the decimal value for 0x2002. By giving "%x" to sscanf, you are specifying the input string as hexadecimal. so, the preceding "0x" is fine.

Is there any char to hexadecimal function for C?

I have a char array with data from a text file and I need to convert it to hexadecimal format.
Is there such a function for C language.
Thank you in advance!
If I understand the question correctly (no guarantees there), you have a text string representing a number in decimal format ("1234"), and you want to convert it to a string in hexadecimal format ("4d2").
Assuming that's correct, your best bet will be to convert the input string to an integer using either sscanf() or strtol(), then use sprintf() with the %x conversion specifier to write the hex version to another string:
char text[] = "1234";
char result[SIZE]; // where SIZE is big enough to hold any converted value
int val;
val = (int) strtol(text, NULL, 0); // error checking omitted for brevity
sprintf(result, "%x", val);
I am assuming that you want to be able to display the hex values of individual byes in your array, sort of like the output of a dump command. This is a method of displaying one byte from that array.
The leading zero on the format is needed to guarantee consistent width on output.
You can upper or lower case the X, to get upper or lower case representations.
I recommend treating them as unsigned, so there is no confusion about sign bits.
unsigned char c = 0x41;
printf("%02X", c);
You can use atoi and sprintf / snprintf. Here's a simple example.
char* c = "23";
int number = atoi(c);
snprintf( buf, sizeof(buf), "%x", number );

Resources