BitConverter VS ToString for Hex

≯℡__Kan透↙ 提交于 2020-01-03 17:16:13

问题


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

回答1:


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.




回答2:


I would guess because GetBytes returns an array of bytes which BitConverter.ToString formatted - in my opinion - rather nicely

And also keep in mind that the bitwise represantattion may be different from the value! This depends where the most signigicant byte sits!

hth



来源:https://stackoverflow.com/questions/6107121/bitconverter-vs-tostring-for-hex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!