7

Shouldn't 0x00000100 = 4.

I understand that 0x00000001 = 1 since 2^0 and 0x00000010 = 2 since 2^1. What is wrong with my thinking?

initVariable(&variable1, "variable1", "1, 2, 3", 0x00000100);

assertIntegerEquals(variable1.address, 4); // 0x00000100 = 4?

My assertion fails because it says that 256 != 4

letter Q
  • 14,735
  • 33
  • 79
  • 118

6 Answers6

29

Numbers that begin with 0x are interpreted as hexadecimal (base 16) in C.

So 0x10 == 16, and 0x100 == 256, 0x10000 == 65536, etc.

Powers of two are:

  • 20 = 0x1
  • 21 = 0x2
  • 22 = 0x4
  • 23 = 0x8
  • 24 = 0x10
  • 25 = 0x20
  • 26 = 0x40
  • 27 = 0x80
  • 28 = 0x100
S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
11

No, the 0x means hexadecimal (i.e. base-16) and not binary, which is what you seem to be confusing it with.

If you want to use binary literals in your code, then see this SO question, which mentions the gcc extension that allows 0b00000100 to be used to represent 4 in binary.

Community
  • 1
  • 1
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
8

0x00000100 is in base-16 because 0x prefix means you are using hexadecimal notation.

So 0x00000001 = 1*160 = 1, 0x00000010 = 1*161, 0x00000100 = 1*162 = 256 and 0x00000123 = 1*162 + 2*161 + 3*160 = 256 + 32 + 3 = 291

To play with base-2, base-10 and base-16 notation, you can try this site: http://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html

Korchkidu
  • 4,908
  • 8
  • 49
  • 69
6

The 0x prefix means hexadecimal

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
3

0x00000100 (hex) = 0000 0000 0000 0000 0000 0001 0000 0000 (binary) = 256 (decimal)

Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
1

0x prefix is hexadecimal 0x00000100 = 256 base 16

00000100 = 00000120100

= 1 * 162 + 0*161 + 0*0

=1 * 256 + 0*16 + 0*1

= 256 + 0 + 0

=256

shas
  • 703
  • 2
  • 8
  • 31