小字符串的快速开源校验和 [英] Fast open source checksum for small strings

查看:17
本文介绍了小字符串的快速开源校验和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于小字符串(20-500 个字符),我需要一个快速校验和(尽可能快).

I need a quick checksum (as fast as possilbe) for small strings (20-500 chars).

我需要源代码,而且它必须很小!(最大约 100 LOC)

I need the source code and that must be small! (about 100 LOC max)

如果它可以在 Base32/64 中生成字符串.(或类似的东西)这将是完美的.基本上校验和不能使用任何坏"字符..你知道..通常的 (){}[].,;:/+-|等等

If it could generate strings in Base32/64. (or something similar) it would be perfect. Basically the checksums cannot use any "bad" chars.. you know.. the usual (){}[].,;:/+-| etc

澄清

它可能是强/弱,这并不重要,因为它仅用于幕后目的.

It could be strong/weak, that really doesn't matter since it is only for behind-the-scenes purposes.

它不需要包含原始字符串的所有数据,因为我只会与生成的校验和进行比较,我不希望有任何解密".

It need not contain all the data of the original string since I will be only doing comparison with generated checksums, I don't expect any sort of "decryption".

推荐答案

用C快速实现,我这边没有版权,随便用吧.但请注意,这是一个非常弱的校验和",所以不要将它用于严肃的事情:) - 但这就是你想要的,不是吗?

Quick implementation in C, no copyrights from my side, so use it as you wish. But please note that this is a very weak "checksum", so don't use it for serious things :) - but that's what you wanted, isn't it?

这将返回一个 32 位整数校验和,编码为包含其十六进制值的字符串.如果校验和函数不能满足您的需求,您可以将 chk += ((int)(str[i]) * (i + 1)); 行更改为更好的(fe 乘法),加法和按位旋转会更好).

This returns an 32-bit integer checksum encoded as an string containing its hex value. If the checksum function doesn't satisfy your needs, you can change the chk += ((int)(str[i]) * (i + 1)); line to something better (f.e. multiplication, addition and bitwise rotating would be much better).

按照hughdbrown的建议和他链接的答案之一,我更改了for 循环,因此它不会在每次迭代时调用 strlen.

Following hughdbrown's advice and one of the answers he linked, I changed the for loop so it doesn't call strlen with every iteration.

#include <stdio.h>
#include <stdlib.h>
#include <string>

char* hextab = "0123456789ABCDEF";

char* encode_int(int i) {
  char* c = (char*)malloc(sizeof(char) * 9);

  for (int j = 0; j < 4; j++) {
    c[(j << 1)] = hextab[((i % 256) >> 4)];
    c[(j << 1) + 1] = hextab[((i % 256) % 16)];

    i = (i >> 8);
  }
  c[8] = 0;

  return c;
}

int checksum(char* str) {
  int i;
  int chk = 0x12345678;

  for (i = 0; str[i] != ''; i++) {
    chk += ((int)(str[i]) * (i + 1));
  }

  return chk;
}

int main() {
  char* str1 = "Teststring";
  char* str2 = "Teststring2";

  printf("string: %s, checksum string: %s
", str1, encode_int(checksum(str1)));
  printf("string: %s, checksum string: %s
", str2, encode_int(checksum(str2)));

  return 0;
}

这篇关于小字符串的快速开源校验和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆