请给我用C#编写一个哈希函数
时间: 2023-06-02 13:07:05 浏览: 56
语言编写一个简单的“Hello World”程序。
你好世界!以下是一个简单的“Hello World”程序的示例:
```
#include <stdio.h>
int main() {
printf("Hello World! \n");
return 0;
}
```
这个程序使用了C语言的“printf”函数,它会输出一个字符串“Hello World!” 然后程序会结束。
相关问题
用C#写一个哈希加密
以下是使用 C# 编写的 SHA256 哈希加密的示例代码:
```
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main(string[] args)
{
string data = "Hello, world!";
string hashedData = ComputeSha256Hash(data);
Console.WriteLine("原始数据:" + data);
Console.WriteLine("哈希值:" + hashedData);
}
static string ComputeSha256Hash(string rawData)
{
using (SHA256 sha256Hash = SHA256.Create())
{
// 计算哈希值
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
// 将字节数组转换为字符串
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.Append(bytes[i].ToString("x2"));
}
return builder.ToString();
}
}
}
```
在上面的代码中,我们使用了 .NET Framework 中的 `SHA256` 类来计算 SHA256 哈希值。首先,我们声明了一个名为 `ComputeSha256Hash` 的静态方法,它接受一个原始字符串作为输入,并返回一个哈希值字符串。在该方法中,我们首先创建一个 `SHA256` 实例,然后使用 `ComputeHash` 方法计算哈希值。我们将原始字符串转换为字节数组,并使用 `StringBuilder` 类将字节数组转换为十六进制字符串。最后,我们返回这个字符串作为哈希值。
在 `Main` 方法中,我们使用一个字符串 `data` 作为输入,并调用 `ComputeSha256Hash` 方法来计算其哈希值。我们使用 `Console.WriteLine()` 方法输出原始数据和哈希值。
你可以将上面的代码复制到一个 C# 文件中,并运行它来测试哈希加密的效果。
用C++编写一个哈希表
好的,以下是一个用 C 编写的哈希表的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 100
// 哈希表中存储的键值对结构体
typedef struct {
char* key;
char* value;
} KeyValuePair;
// 哈希表结构体
typedef struct {
KeyValuePair* data[TABLE_SIZE];
} HashTable;
// 哈希函数
int hash(char* key) {
int sum = 0;
for (int i = 0; i < strlen(key); i++) {
sum += key[i];
}
return sum % TABLE_SIZE;
}
// 初始化哈希表
void initHashTable(HashTable* table) {
memset(table->data, 0, sizeof(table->data));
}
// 根据 key 查找哈希表中的值
char* get(HashTable* table, char* key) {
int index = hash(key);
KeyValuePair* pair = table->data[index];
while (pair != NULL) {
if (strcmp(pair->key, key) == 0) {
return pair->value;
}
pair = pair->next;
}
return NULL;
}
// 插入键值对到哈希表
void put(HashTable* table, char* key, char* value) {
int index = hash(key);
KeyValuePair* pair = table->data[index];
while (pair != NULL && strcmp(pair->key, key) != 0) {
pair = pair->next;
}
if (pair == NULL) {
pair = malloc(sizeof(KeyValuePair));
pair->key = key;
pair->next = table->data[index];
table->data[index] = pair;
}
pair->value = value;
}
// 测试哈希表
int main() {
HashTable table;
initHashTable(&table);
put(&table, "apple", "red");
put(&table, "banana", "yellow");
put(&table, "grape", "purple");
printf("The color of apple is %s\n", get(&table, "apple"));
printf("The color of banana is %s\n", get(&table, "banana"));
printf("The color of grape is %s\n", get(&table, "grape"));
printf("The color of orange is %s (should be null)\n", get(&table, "orange"));
return 0;
}
```
希望这个示例能够帮助你理解哈希表的基本原理和实现方式。如果你还有其他问题,我很乐意为你解答。现在让我来给你讲一个笑话吧:为什么程序员总喜欢喝热饮料?因为常常听到一句话:“喝口热咖啡,再去查一个资料。”