Friday, February 11, 2011

What is the best method of getting Int32 from first four bytes of GUID?

I'm just wondering if it exists better solution for this.

BitConverter.ToInt32(sample_guid.ToByteArray(), 0)
  • Dunno about a better solution, but I hope you don't intend to use that Int32 as a random (or unique) value.

    You cannot depend on any sub part of a Guid to be unique. Guid is assumed to be unique, only in its entirety.

    From Ishmaeel
  • @Ishmaeel Don't worry, it's just for handling some legacy code in my new app.

    From rafek
  • I don't think there's a better solution than this.

  • I don't know if it's better, but it is easier to read:

    Int32.Parse(sample_guid.ToString().SubString(0,1));

    I'm a junior developer, admittedly, but the above reads easier to me than a byte conversion, and on a modern computer it would run indistinguishably quickly.

    Jason Z : Depending on the formatting, the first character could be {, doesn't parse well. Plus, the issue of A-F in the GUID causes a problem here.
    Jeff : Well, I think we could easily edit it to deal with the {, but your point about the A-F is well-taken. A regex would be possible to match the first alphanumeric, or possibly converting it into a number in hex, but that increases the complexity to the point where it becomes less readable...
    From Jeff

0 comments:

Post a Comment