我想先把一个hash256对象转换成一个32字节的整数,然后再打包成一个bytearray。
>>> import hashlib
>>> hashobj = hashlib.sha256('something')
>>> val_hex = hashobj.hexdigest()
>>> print val_hex
3fc9b689459d738f8c88a3a48aa9e33542016b7a4052e001aaa536fca74813cb
>>> print len(val_hex)
64
Run Code Online (Sandbox Code Playgroud)
十六进制字符串是 64 字节而不是 32 字节,这不是我想要的。
>>> val = hashobj.digest()
>>> print val
???E?s????????5Bkz@R???6??H?
>>> print len(val)
32
Run Code Online (Sandbox Code Playgroud)
这是一个 32 字节的字符串,我想将其转换为 32 字节的整数。
当我尝试时,它给了我一条错误消息:
>>> val_int = int(val, 10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '?\xc9\xb6\x89E\x9ds\x8f\x8c\x88\xa3\xa4\x8a\xa9\xe35B\x01kz@R\xe0\x01\xaa\xa56\xfc\xa7H\x13\xcb'
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能得到我的 int_val?
以及如何使用 struct 将其(32 字节)打包为字节数组?我发现python结构文档中最长的格式是'Q',它只有8个字节。
非常感谢。
编辑:
我有一个很大的数字,C 本身没有它的类型。我必须使用字符数组来保存它。作为示例,我创建了一个 32 字节数组。它代表一个大数,最大可达 2 ^ 256。
unsigned char num[32]; // The size could be any number for this question.
Run Code Online (Sandbox Code Playgroud)
我想对其进行模运算,例如,我想用一个小除数对大数进行模运算并得到一个整数类型的结果。
int divisor = 1234; // Note that the divisor is much smaller than the big number
int result;
// do something here
// to produce a result
// like result = number mod divisor
Run Code Online (Sandbox Code Playgroud)
我不想使用其他库。我该怎么做?
我正在尝试在我的代码中使用 AES-CTR-128。我使用Python 2.7并利用该cryptography模块进行加密。
我需要设置特定的计数器值,例如 counter_iv = 112。当我尝试时
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
backend = default_backend()
key = os.urandom(32)
counter_iv = 112
cipher = Cipher(algorithms.AES(key), modes.CTR(counter_iv), backend=backend)
encryptor = cipher.encryptor()
ciphertext = encryptor.update(b"a secret message") + encryptor.finalize()
Run Code Online (Sandbox Code Playgroud)
这给了我一条错误消息:
Run Code Online (Sandbox Code Playgroud)Traceback (most recent call last): File "aestest.py", line 14, in <module> cipher = Cipher(algorithms.AES(key), modes.CTR(counter_iv), backend=backend) File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/primitives/ciphers/modes.py", line 139, in __init__ raise TypeError("nonce must be bytes") TypeError: nonce must be bytes
我认为它告诉我 counter_iv …
我写了一个程序,有2个线程做同样的事情,但我发现每个线程的吞吐量比我只生成一个线程慢.然后我写这个简单的测试,看看这是我的问题,还是因为系统.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
/*
* Function: run_add
* -----------------------
* Do addition operation for iteration ^ 3 times
*
* returns: void
*/
void *run_add(void *ptr) {
clock_t t1, t2;
t1 = clock();
int sum = 0;
int i = 0, j = 0, k = 0;
int iteration = 1000;
long total = iteration * iteration * iteration;
for (i = 0; i < iteration; i++) {
for (j = 0; j < …Run Code Online (Sandbox Code Playgroud)