了解C#中的十六进制和字节 [英] Understanding hexadecimals and bytes in C#

查看:334
本文介绍了了解C#中的十六进制和字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎对在C#(或一般编程)中计算和使用十六进制和字节值缺乏基本的了解.

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

我想知道如何从诸如字符串和RGB颜色之类的源中计算十六进制值和字节(0x-)(例如如何确定R255 G0 B0的0x代码是什么?)

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 ?)

为什么我们使用FF之类的东西,是为了补偿以10为基数的系统得到的数字,例如10?

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

推荐答案

十六进制的基数为16,因此不是从0到9进行计数,而是从0到F进行计数.通常在十六进制常量前加上0x作为前缀.因此,

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

字节是计算机上值的典型存储单位,在大多数现代系统中,一个字节包含8位.请注意,bit实际上是binary digit的意思,因此从中我们可以得出一个字节的最大值为11111111二进制.即十六进制的0xFF,或十进制的255.因此,一个字节可以用最少两个十六进制字符表示.然后,典型的4字节int是8个十六进制字符,例如0xDEADBEEF.

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值通常包装有3个字节的值,即RGB.因此,

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)

对于我的十六进制计算,我喜欢使用python作为计算器:

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

对于RGB示例,我可以演示如何使用位移位轻松计算这些值:

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

这篇关于了解C#中的十六进制和字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆