The Powers of 10 - c

#include <stdio.h>
#include <stdlib.h>
#define SIZEOF(arr) (sizeof(arr) / sizeof(arr[0]))
#define PrintInt(expr) printf("%s:%d\n",#expr,(expr))
int main()
{
/* The powers of 10 */
int pot[] = {
0001,
0010,
0100,
1000
};
int i;
for(i=0;i<SIZEOF(pot);i++)
PrintInt(pot[i]);
return 0;
}
The output of the following code is
pot[i]:1
pot[i]:8
pot[i]:64
pot[i]:1000
why does it give such output??`

Prefixing a numeric literal in C with a 0 digit will output it in Octal, which is a base 8 numeric system.
Oct(1) = Dec(1)
Oct(10) = Dec(8)
Oct(100) = Dec(64)
That's where your numbers are coming from.
FYI, Hexadecimal literals are prefixed with 0x and binary literals are prefixed with 0b (IIRC)
Edit: To actually answer your question, just remove the leading zeroes from the numbers and it should give you the desired output.

Number literals which start with a zero are interpreted as being in octal – base 8. So the first three numbers are octal 1, 10 and 100 (which are 1, 8 and 64 in base-10); the last number is base 10.

Based on how your constants are defined, and how your question is worded, I think you want hex. Prefix your values with "0x":
int pot[] = {
0x0001,
0x0010,
0x0100,
0x1000
;

Related

value in array will be printed as 0 even after changing it in c

So I made a custom type by using typedef unsigned char byte;, and then declared an array of it, like using byte mem[255];. I used mem[0] = 0x10100000; to init the first value, but when I print it using printf("%d", mem[0]); I get 0. Why?
An unsigned char can typically only hold values between 0 and 255. The hex value 0x10100000 is well out of range for that type, so (essentially) only the low-order byte of that value is used, which is 0.
Presumably you wanted to use a binary constant. Not all compilers support that, but those that do would specify it as 0b10100000. For those than don't you can use the hex value 0xA0.
You're assigning it the hexidecimal number 0x10100000 which is far larger than a single character, and thus can't be stored in a byte. If you want to use a binary number, and your compiler supports this, you might try using 0b10100000 instead.
unsigned char can only hold the value of ((1 << CHAR_BIT) - 1)
You can check what is the maximum value yourself
#include <stdio.h>
#include <limits.h>
int main(void)
{
printf("%u\n", (1 << CHAR_BIT) - 1);
}
On most systems it is 255 or 0xff.
When you assign the unsigned char with 0x10100000 only the lowest two hex digits will be assigned (in your case 0x00).
If you wanted to copy all the bytes from the 0x10100000 to the byte array mem you defined, the assignment will not work. You need to copy then instead:
#include <stdio.h>
#include <limits.h>
#include <string.h>
typedef unsigned char byte;
int main(void)
{
byte mem[100];
memcpy(mem, &(unsigned){0x10100000}, sizeof(0x10100000));
for(size_t index = 0; index < sizeof(0x10100000); index++)
{
printf("mem[%zu] = 0x%hhx\n", index, mem[index]);
}
}
Output:
mem[0] = 0x0
mem[1] = 0x0
mem[2] = 0x10
mem[3] = 0x10
https://godbolt.org/z/cGYa8MTef
Why in this order? Because the machine, where godbolt is run, uses little endioan. https://en.wikipedia.org/wiki/Endianness
0x prefix means that number hexadecimal. If you wanted to use binary number then gcc supports 0b prefix which is not standard.
mem[0] = 0b10100000
You can also create .h file
#define b00000000 0
#define b00000001 1
#define b00000010 2
#define b00000011 3
/* .... */
#define b11111110 254
#define b11111110 255
and use those definitions portable way
mem[0] = b10100000;
You can't fit a 32 bit value inside an 8 bit variable (mem[0]). Do you perhaps mean to do this?
*(int *)mem = 0x10100000;

How to print in HEX format the MSBs bits when they're equal to 0

I need to print variables using HEX format.
The problem is when my variables are little the MSBs equal 0 so they are not printed.
ex: uint16_t var = 10; // (0x000A)h
-> I need to print "000A" but no matter what I do it always prints just 'A'
How could I get it to work?
You can add a leading 0 to the width specifier in order to force printf to add leading zeros (at least, you can in C and C++ - not entirely sure about other languages that use the function).
For example, in C, the following:
#include <stdio.h>
#include <stdint.h>
int main()
{
uint16_t a = 10; // 0xA
printf("%04X\n", a);
// ^ width specifier: display as 4 digits
// ^ this signals to add leading zeros to pad to at least "n" digits
return 0;
}
will display:
000A

Why C programming gives different output? [duplicate]

This question already has answers here:
How does C Handle Integer Literals with Leading Zeros, and What About atoi?
(8 answers)
Closed 3 years ago.
I got unexpected outputs, and I could not figure out the reason.
#include <stdio.h>
int main() {
int a = 0100;
int b = 010;
int c = 1111;
int d = 01111;
printf("0100 => %d, 010 => %d, 1111 => %d, 01111=> %d\n", a, b, c, d);
}
Output:
0100 => 64, 010 => 8, 1111 => 1111, 01111=> 585
Why does such output occur?
In C, putting either 0x or 0 before an integer literal value will cause the compiler to interpret the number in base 16 (hexadecimal) and base 8 (octal), respectively.
Normally, we interpret and read numbers in base 10 (decimal). However, we sometimes will use these other bases because they are useful powers of 2 that can represent groups of bits (1 hexadecimal digit = 4 bits, 1 octal digit = 3 bits), and bit manipulation is something that C wants to provide. This is why you'll see something like char be represented with 2 hexadecimal digits (e.g. 0x12) to set a single char to be a specific bit sequence.
If you wanted to verify this, printf also allows you to output int in hexadecimal and octal as well using %x and %o respectively instead of %d.
#include <stdio.h>
int main()
{
int a = 0100;
int b = 010;
int c = 1111;
int d = 01111;
printf("0100 => %o, 010 => %o, 1111 => %d, 01111=> %o\n", a,b,c,d);
}
If you run this program, you'll get the following:
gcc -ansi -O2 -Wall main.c && ./a.out
0100 => 100, 010 => 10, 1111 => 1111, 01111=> 1111
...which is exactly what you set the values to in the program, just without the prefixes. You just mistakenly used another integer encoding by accident on assignment in the original code, and used a different one to output the value.
0 prefix gives you octal, and you tried to print decimal.

Convert FFFFFF to decimal value (C language)

I am trying to convert a string representing a 24-bit hexadecimal number (FFFFFF) to its decimal equivalent (-1). Could anyone help me understand why the following code does not return -1?
Thanks, LC
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
char temp_str[] = "FFFFFF";
long value;
value = strtol(temp_str, NULL, 16);
printf("value is %ld\n", value);
}
It seems like your input is the 24-bit 2's complement representation of the number, but strtol does not handle negative numbers in this way (and even if it did, it has no way of knowing that you meant a 24-bit representation). It only determines the sign of its output based on the existence of a - sign.
You can modify your code to get the result you want by adding this after the strtol:
if (value > 0x7fffff)
value -= 0x1000000;
Of course, this will only work for a 24-bit representation, other sizes will need different constants.
Hacker's delight covers this under sign extension.
For your 24 bit number, the sign bit is the 24th bit from the right and if it was set the hex value would be 0x800000.
The book suggests these:
((x + 0x800000) & 0xFFFFFF) - 0x800000
or
((x & 0xFFFFFF) xor 0x800000) - 0x800000
From your question I would say that your number is never going to be more than 24 bits so I would use the second option in your code as follows:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
char temp_str[] = "FFFFFF";
long value;
value = strtol(temp_str, NULL, 16);
value = (value ^ 0x800000) - 0x800000; // Notice that I'm not using the & 0xFFFFFF since I assumed that the number won't have more than 24 bits.
printf("value is %ld\n", value);
}
Edit 1:
I fear that my original answer, though technically sound did not answer the posed question.
Could anyone help me understand why the following code does not return -1?
Others have already covered this by the time I answered but I will restate it here anyway.
Your string is "FFFFFF", it consists of 6 hex digits. Each hex digit represents 4 bits, therefore your string represents a 24 bit number.
Your variable long value is of type long which normally corresponds to your CPU's word width (32bit or 64bit). Since these days long can be either 32 bits or 64 bits depending on your architecture you are not guaranteed to get -1 unless you give exactly the right number of hex digits.
If long on your machine is 32 bits then two things are true:
sizeof(long) will return 4
Using "FFFFFFFF" will return -1
If long on your machine is 64 bits then two things are true:
sizeof(long) will return 8
Using "FFFFFFFFFFFFFFFF" will return -1
Digression
This then lead me down a completely different path. We can generalize this and make a program that constructs a string for your machine, such that it will always return -1 from a string.
#include #include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
const char* ff = "FF";
char temp[sizeof(long) * 2 + 1]; // Ensure that the string can store enough hex digits so that we can populate the entire width of long. Include 1 byte for '\0'
int i;
long value;
/* Fill the temp array with FF */
for (i = 0; i < sizeof(long); ++i)
{
strcpy(&temp[i * 2], ff);
}
value = strtol(temp, NULL, 16);
printf("value of %s is %ld\n", temp, value);
}
This is a bad way to get a -1 result since the clear option is to just use
long value = -1;
but I will assume that this was simply an academic exercise.
Don't think as a computer now, just convery (FFFFFF)16 to decimal use ordinary math thinking. This is not about two's complement negative notation.
Because you run this program on 32- or 64-bit machine, not 24-bit. 0xffffff is actually 0x00ffffff, which is 16777215 in decimal.
Hex representation of -1 is 0xffffffff or 0xffffffffffffffff.

How to display hexadecimal numbers in C?

I have a list of numbers as below:
0, 16, 32, 48 ...
I need to output those numbers in hexadecimal as:
0000,0010,0020,0030,0040 ...
I have tried solution such as:
printf("%.4x",a); // where a is an integer
but the result that I got is:
0000, 0001, 0002, 0003, 0004 ...
I think I'm close there. Can anybody help as I'm not
so good at printf in C.
Thanks.
Try:
printf("%04x",a);
0 - Left-pads the number with
zeroes (0) instead of spaces, where
padding is specified.
4 (width) - Minimum number of
characters to be printed. If the
value to be printed is shorter than
this number, the result is right justified
within this width by padding on the left
with the pad character. By default this is
a blank space, but the leading zero we used
specifies a zero as the pad char.
The value is not truncated even if the result is
larger.
x - Specifier for hexadecimal
integer.
More here
i use it like this:
printf("my number is 0x%02X\n",number);
// output: my number is 0x4A
Just change number "2" to any number of chars You want to print ;)
Your code has no problem. It does print the way you want. Alternatively, you can do this:
printf("%04x",a);
You can use the following snippet code:
#include<stdio.h>
int main(int argc, char *argv[]){
unsigned int i;
printf("decimal hexadecimal\n");
for (i = 0; i <= 256; i+=16)
printf("%04d 0x%04X\n", i, i);
return 0;
}
It prints both decimal and hexadecimal numbers in 4 places with zero padding.

Resources