How to convert this hex string into a long?

不打扰是莪最后的温柔 提交于 2020-04-12 09:12:30

问题


I have: "0xE94C827CEB" in hex but as a string.

Which is: 1002011000043 (dd mm yyyy HH mm ss)

Unfortunately I don't know how to do the conversion if I only have it in string format, and I don't have a Convert.ToLong("0xE94C827CEB", 16) function because I'm using the .NET Micro Framework (also, don't have NumberStyles namespace available.)

Is there a function out there that will convert this for me?

Thanks


回答1:


I don't know of any function to do it, but I think you can do it quite simply by splitting the hex string and passing each part through Convert.ToInt32():

int part1 = Convert.ToInt32("E9", 16)
int part2 = Convert.ToInt32("4C827CEB", 16) //the last 4 bytes
long result = part1 * 4294967296 + part2  //4294967296 being 2^32. Result = 1002011000043



回答2:


For those of you looking for the answer using the full .NET framework for pc.

long answer = Convert.ToInt64("E94C827CEB",16);

see: MSDN Documentation




回答3:


Kick it old-school and roll your your own. This is not exactly rocket science here:

public ulong HexLiteral2Unsigned( string hex )
{
    if ( string.IsNullOrEmpty(hex) ) throw new ArgumentException("hex") ;

    int i = hex.Length > 1 && hex[0]=='0' && (hex[1]=='x'||hex[1]=='X') ? 2 : 0 ;
    ulong value = 0 ;

    while ( i < hex.Length )
    {
        uint x = hex[i++] ;

        if      ( x >= '0' && x <= '9' ) x =   x - '0' ;
        else if ( x >= 'A' && x <= 'F' ) x = ( x - 'A' ) + 10 ;
        else if ( x >= 'a' && x <= 'f' ) x = ( x - 'a' ) + 10 ;
        else throw new ArgumentOutOfRangeException("hex") ;

        value = 16*value + x ;

    }

    return value ;
}


来源:https://stackoverflow.com/questions/16569951/how-to-convert-this-hex-string-into-a-long

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