Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding hexadecimals and bytes in C#

Tags:

c#

hex

binary

byte

I seem to lack a fundemental understanding of calculating and using hex and byte values in C# (or programming in general).

I'd like to know how to calculate hex values and bytes (0x--) from sources such as strings and RGB colors (like how do I figure out what the 0x code is for R255 G0 B0 ?)

Why do we use things like FF, is it to compensate for the base 10 system to get a number like 10?

like image 705
Daniel Minnaar Avatar asked Aug 22 '12 21:08

Daniel Minnaar


1 Answers

Hexadecimal is base 16, so instead of counting from 0 to 9, we count from 0 to F. And we generally prefix hex constants with 0x. Thus,

Hex      Dec
-------------
0x00  =  0
0x09  =  9
0x0A  =  10
0x0F  =  15
0x10  =  16
0x200 =  512

A byte is the typical unit of storage for values on a computer, and on most all modern systems, a byte contains 8 bits. Note that bit actually means binary digit, so from this, we gather that a byte has a maximum value of 11111111 binary. That is 0xFF hex, or 255 decimal. Thus, one byte can be represented by a minimum of two hexadecimal characters. A typical 4-byte int is then 8 hex characters, like 0xDEADBEEF.

RGB values are typically packed with 3 byte values, in that order, RGB. Thus,

R=255 G=0 B=0    =>  R=0xFF G=0x00 B=0x00  =>  0xFF0000  or #FF0000 (html)
R=66  G=0 B=248  =>  R=0x42 G=0x00 B=0xF8  =>  0x4200F8  or #4200F8 (html)

For my hex calculations, I like to use python as my calculator:

>>> a = 0x427FB
>>> b = 700
>>> a + b
273079
>>>
>>> hex(a + b)
'0x42ab7'
>>>
>>> bin(a + b)
'0b1000010101010110111'
>>>

For the RGB example, I can demonstrate how we could use bit-shifting to easily calculate those values:

>>> R=66
>>> G=0
>>> B=248
>>>
>>> hex( R<<16 | G<<8 | B )
'0x4200f8'
>>>
like image 67
Jonathon Reinhart Avatar answered Oct 18 '22 23:10

Jonathon Reinhart