BitConverter VS ToString用于十六进制 [英] BitConverter VS ToString for Hex

查看:194
本文介绍了BitConverter VS ToString用于十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道是否有人可以解释为什么下面两行代码返回不同结果?什么原因导致颠倒值?这是否与endianness有关?

  int.MaxValue.ToString(X)//结果:7FFFFFFF 
BitConverter.ToString(BitConverter.GetBytes (int.MaxValue))//结果:FF-FF-FF-7F


解决方案

int.MaxValue.ToString(X)输出 7FFFFFFF ,也就是数字 2147483647 作为一个整体 另一方面, BitConverter.GetBytes 在内存中返回一个代表 2147483647 的字节数组。在你的机器上,这个数字存储在little-endian(最后一个字节)中。并且 BitConverter.ToString 分别对每个字节进行操作,因此不会重新排序输出以保持与上述相同,从而保留内存顺序。



然而这两个值是相同的: 7F-FF-FF-FF 对于 int.MaxValue ,在big-endian中, FF-FF-FF-7F BitConverter ,小端。相同的数字。


Just wondering if someone could explain why the two following lines of code return "different" results? What causes the reversed values? Is this something to do with endianness?

int.MaxValue.ToString("X") //Result: 7FFFFFFF
BitConverter.ToString(BitConverter.GetBytes(int.MaxValue)) //Result: FF-FF-FF-7F

解决方案

int.MaxValue.ToString("X") outputs 7FFFFFFF, that is, the number 2147483647 as a whole.

On the other hand, BitConverter.GetBytes returns an array of bytes representing 2147483647 in memory. On your machine, this number is stored in little-endian (highest byte last). And BitConverter.ToString operates separately on each byte, therefore not reordering output to give the same as above, thus preserving the memory order.

However the two values are the same : 7F-FF-FF-FF for int.MaxValue, in big-endian, and FF-FF-FF-7F for BitConverter, in little-endian. Same number.

这篇关于BitConverter VS ToString用于十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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