Skip to content

Instantly share code, notes, and snippets.

@danzek
Last active January 2, 2018 21:37
Show Gist options
  • Select an option

  • Save danzek/8bc7820dfefa025e681bc4f4a7a02627 to your computer and use it in GitHub Desktop.

Select an option

Save danzek/8bc7820dfefa025e681bc4f4a7a02627 to your computer and use it in GitHub Desktop.
Google Analytics Domain Hash Calculator - Urchin Tracking Module A (utma)
// GoogleAnalyticsDomainHashCalculator.cpp
//
// NOTE: I turned this into a robust CLI tool: https://github.com/danzek/gadhash
//
// Calculates Google Analytics Domain Hash given domain name
// =========================================================
// This corresponds to the first value after "utma=" up until the first dot ('.')
// e.g. in "utma=173272373.nnnnnnn", the domain hash is 173272373 ("google.com")
// do not include the protocol in url (e.g., "http://")
//
// based on answers found at https://stackoverflow.com/q/4821627/
// see https://developers.google.com/analytics/devguides/collection/analyticsjs/cookie-usage
/*
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <climits>
int googleAnalyticsDomainHash(std::string domain)
{
int a = 1;
int c = 0;
int h, o;
if (!domain.empty()) {
a = 0;
// domain.length() returns a ulong which could overflow h
// check for this unlikely event and return 0 to prevent
if (domain.length() > INT_MAX) {
return 0;
}
for (h = domain.length() - 1; h >= 0; h--) {
o = domain[h];
a = (a << 6 & 268435455) + o + (o << 14);
c = a & 266338304;
a = c != 0 ? a ^ c >> 21 : a;
}
}
return a;
}
int main()
{
std::string domain = "google.com";
std::cout << googleAnalyticsDomainHash(domain) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment