Tes4Mod:Hash Calculation

Overview
These are examples of code to calculate the hash used in Tes4Mod and Tes5Mod archive formats. The hash cannot be calculated using / (forward slashes) or upper case characters. Forward slashes must be changed to backslashes and upper case characters must be converted to lower case. Folder hash values must not include leading or trailing slashes. While some folder names contain a file extension (e.g. textures\actors\character\facegendata\facetint\skyrim.esm\), this must not be treated as a file extension in the calculation. Some parts of the algorithm need to perform calculations on the extension separately from the filename. The filename substring must be only the filename with no slashes or extension (e.g. meshes\animbehaviors\doors\doortemplate01.hkx -> doortemplate01). The extension must include the '.' .

See also
Tes4Mod BSA File Format
Tes5Mod Archive File Format

Pure C
This was developed by x79 based on the Python version below as well as Ethatron's c++ version in BSAOpt and TimeSlips code in NifTools.
 // pass a filename or a folder path
// e.g. GenHash("meshes\\animbehaviors\\doors", 1) or
// GenHash("doortemplate01.hkx", 0)

unsigned long long GenHash(const char *sPath, const int isFolder)
{
	unsigned long long hash = 0;
	unsigned long hash2 = 0;

	char s[255];	// copy into a local array so we don't modify the data that was passed
	strcpy_s(s, 255, sPath);

	// This is a pointer to the file extension, otherwise NULL
	char *pExt = (isFolder) ? 0 : strrchr(s, '.');

	// Length of the filename or folder path
	unsigned int iLen = strnlen_s(s, 0xFF);

	// pointer to the end of the filename or folder path
	char *pEnd = s + iLen;

	// A single loop converts / to \ and anything else to lower case
	for (int iLoop = 0; iLoop   2) ? s[iLen - 2]  

Python
Here's a python version of the hash calculation.
 def tesHash(fileName):
    """Returns tes4's two hash values for filename.
    Based on TimeSlips code with cleanup and pythonization."""
    root,ext = os.path.splitext(fileName.lower()) #--"bob.dds" >> root = "bob", ext = ".dds"
    #--Hash1
    chars = map(ord,root) #--'bob' >> chars = [98,111,98]
    hash1 = chars[-1] | (0,chars[-2])[len(chars)>2] 

C++
This code comes directly from BSAOpt v2.0 by Ethatron
 /* Version: MPL 1.1/LGPL 3.0
 *
 * "The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * 
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * The Original Code is BSAopt.
 *
 * The Initial Developer of the Original Code is
 * Ethatron  . Portions created by The Initial
 * Developer are Copyright (C) 2011 The Initial Developer.
 * All Rights Reserved.
 *
 * Alternatively, the contents of this file may be used under the terms
 * of the GNU Library General Public License Version 3 license (the
 * "LGPL License"), in which case the provisions of LGPL License are
 * applicable instead of those above. If you wish to allow use of your
 * version of this file only under the terms of the LGPL License and not
 * to allow others to use your version of this file under the MPL,
 * indicate your decision by deleting the provisions above and replace
 * them with the notice and other provisions required by the LGPL License.
 * If you do not delete the provisions above, a recipient may use your
 * version of this file under either the MPL or the LGPL License."
 */

unsigned int GenOBHashStr(string s) {
  unsigned int hash = 0;

  for (size_t i = 0; i   0) {
    hash = (unsigned __int64)(
      (((unsigned char)fle[fle.length() - 1]) * 0x1) +
      ((fle.length() > 2 ? (unsigned char)fle[fle.length() - 2] : (unsigned char)0) * 0x100) +
      (fle.length() * 0x10000) +
      (((unsigned char)fle[0]) * 0x1000000)
    );

    if (fle.length() > 3) {
      hash += (unsigned __int64)(GenOBHashStr(fle.substr(1, fle.length() - 3)) * 0x100000000);
    }
  }

  if (ext.length() > 0) {
    hash += (unsigned __int64)(GenOBHashStr(ext) * 0x100000000LL);

    unsigned char i = 0;
    if (ext == ".nif") i = 1;
    if (ext == ".kf" ) i = 2;
    if (ext == ".dds") i = 3;
    if (ext == ".wav") i = 4;

    if (i != 0) {
      unsigned char a = (unsigned char)(((i & 0xfc )  > 24));
      unsigned char b = (unsigned char)(((i & 0xfe )  >  8));

      hash -= hash & 0xFF00FFFF;
      hash += (unsigned int)((a  

C#
This code is loosely based on   by TimeSlip.
 
private static ulong GetHash(string name)
{
    name = name.Replace('/', '\\');
    return GetHash(Path.ChangeExtension(name, null), Path.GetExtension(name));
}

private static ulong GetHash(string name, string ext)
{
    name = name.ToLowerInvariant();
    ext = ext.ToLowerInvariant();
    var hashBytes = new byte[]
    {
        (byte)(name.Length == 0 ? '\0' : name[name.Length - 1]),
        (byte)(name.Length