Understanding hexadecimals and bytes in C#

后端 未结 4 1952
执笔经年
执笔经年 2021-01-31 06:39

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

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-31 07:12

    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'
    >>>
    

提交回复
热议问题