Failing to convert raw binary/hex to int interpretation - qt

I'm trying to convert raw hex/binary data to different file types.
#include <QByteArray>
#include <QDebug>
int main(int argc, char *argv[])
{
QByteArray package;
package.append( QByteArray::fromHex("a1"));
// "a1" is what is written to the memory, not the string representation of "a1"
qDebug() << package.toHex(); // "a1"
qDebug() << package; // "�"
qDebug() << package.toInt(); // 0
}
Why is the int representation 0 and not 161?

toInt has totally different purpose. It parses string representation of integer. If you want integer representing the value of the first byte of the array, use package[0]. It has char type. I don't remember how qDebug() represents char type, but if you have any problems with it, just static_cast it to unsigned int.

QByteArray::toInt expects that QByteArray contains a string of characters (in ASCII probably), not the binary representation of the number.
If you want to convert binary representation to integer you can use reinterpret_cast:
int i = *reinterpret_cast<quint8*>(package.constData());
Or better use qFromBigEndian/qFromLittleEndian:
int i = qFromLittleEndian<quint8>((const uchar*)package.constData())
In both cases you must know exactly in what format the number is stored and use proper type and endianness.

Related

How to cast double value to first characters

Hello brothers I have work for along time to show the first 6 character from double value so I couldn't do that and I need a simple method, Ex:
Here's my double value I need to cast it: 14.7534343267653.
I need to show the first 7 characters only: 14.7534.
So any body can solve this with a simple way.
The example of doing what you are looking for in C:
#include <stdio.h>
int main(int argc, char *argv[]) {
double number = 14.7534343267653;
printf("%2.4f", number);
return 0;
}
Other languages have identical or very similar format specifiers, so esentially "%2.4f" and some string format() might be what you are looking for.

c language type conversion

I'm not able to understand the output of this simple c code.What happens when we typecast a int value to char pointer?
int main(void) {
int a =320;
char *ptr;
ptr=(char *)&a;
printf("%d",*ptr);
return 0;
}
the output is 64.But I'm unable to figure out the logic.Does the size of the signed char play a role here?
320 is 0x140 in hex. A char is one byte (Two hexadecimal digits), so casting and printing with %d will print the decimal value of 0x40, which happens to be 64.

How to read an unsigned int from a std::unique_ptr<unsigned char[]>?

So basically I'm working on a file reader and the binary file gets loaded into a std::unique_ptr<unsigned char[]> containing all the bytes from the file.
I'm trying to read an unsigned int from the start of it. Usually, if it were just a raw pointer (unsigned char*) it would be as follows:
unsigned int magic = *(reinterpret_cast<unsigned int*>(buffer));
However, I'm currently trying to the same, where buffer is the smart pointer. So far I've came up with this:
unsigned int magic = *(reinterpret_cast<unsigned int*>(classFile_.get()));
Upon outputting magic like this:
std::cout << std::hex << magic;
I get 1. Where I should be getting: 0xbebafeca (this is a Java class file reader, 0xCAFEBABE is the unsigned int magic number).
Any ideas as to why it's not working? I'm also not sure if storing a smart pointer for the unsigned char* is good practice rather than doing something like storing a raw pointer and deleting the allocated array in the de-constructor.

C++: OpenSSL, aes cfb encryption [duplicate]

I tried to implement a "very" simple encryption/decryption example. I need it for a project where I would like to encrypt some user information. I can't encrypt the whole database but only some fields in a table.
The database and most of the rest of the project works, except the encryption:
Here is a simplified version of it:
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
/* ckey and ivec are the two 128-bits keys necessary to
en- and recrypt your data. Note that ckey can be
192 or 256 bits as well
*/
unsigned char ckey[] = "helloworldkey";
unsigned char ivec[] = "goodbyworldkey";
int bytes_read;
unsigned char indata[AES_BLOCK_SIZE];
unsigned char outdata[AES_BLOCK_SIZE];
unsigned char decryptdata[AES_BLOCK_SIZE];
/* data structure that contains the key itself */
AES_KEY keyEn;
/* set the encryption key */
AES_set_encrypt_key(ckey, 128, &keyEn);
/* set where on the 128 bit encrypted block to begin encryption*/
int num = 0;
strcpy( (char*)indata , "Hello World" );
bytes_read = sizeof(indata);
AES_cfb128_encrypt(indata, outdata, bytes_read, &keyEn, ivec, &num, AES_ENCRYPT);
cout << "original data:\t" << indata << endl;
cout << "encrypted data:\t" << outdata << endl;
AES_cfb128_encrypt(outdata, decryptdata, bytes_read, &keyEn, ivec, &num, AES_DECRYPT);
cout << "input data was:\t" << decryptdata << endl;
return 0;
}
But the output of "decrypted" data are some random characters, but they are the same after every execution of the code. outdata changes with every execution...
I tried to debug and search for a solution, but I couldn't find any solution for my problem.
Now my question, what is going wrong here? Or do I completely misunderstand the provided functions?
The problem is that AES_cfb128_encrypt modifies the ivec (it has to in order to allow for chaining). Your solution is to create a copy of the ivec and initialize it before each call to AES_cfb128_encrypt as follows:
const char ivecstr[AES_BLOCK_SIZE] = "goodbyworldkey\0";
unsigned char ivec[AES_BLOCK_SIZE];
memcpy( ivec , ivecstr, AES_BLOCK_SIZE);
Then repeat the memcpy before your second call to AES_cfb128_encrypt.
Note 1: Your initial vector was a byte too short, so I put an explicit additional \0 at the end of it. You should make sure all of your strings are of the correct length when copying or passing them.
Note 2: Any code which uses encryption should REALLY avoid using strcpy or any other copy of unchecked length. It's a hazard.

Create a random string or number in Qt4

Is there any function or something like that by which I can create totally random strings or numbers?
You can create random numbers using qrand. If you need strings, you can convert the int to string. You could also check the QUuid class, which generates Universally Unique Identifiers. Those are not 'totally random', but they are unique.
int number;
int randomValue = qrand() % number;
returns a random number randomValue with 0 <= randomValue < number.
qrand() is declared in QtGlobal which is #included by many other Qt files.
int value;
QString aString = QString::number(value);
converts an integer to QString.
The following example generates alphabetic strings with capital letters from A to Z and length = len.
QString randString(int len)
{
QString str;
str.resize(len);
for (int s = 0; s < len ; ++s)
str[s] = QChar('A' + char(qrand() % ('Z' - 'A')));
return str;
}
This is not a very good method to generate random numbers within a given range. (In fact it's very very bad for most generators )
You are assuming that the low-order bits from the generator are uniformly distributed. This is not the case with most generators. In most generators the randomness occurs in the high order bits.
By using the remainder after divisions you are in effect throwing out the randomness.
You should scale using multiplication and division. Not using the modulo operator.
eg
my_numbe r= start_required + ( generator_output * range_required)/generator_maximum;
If generator_output is in [0, generator_maximum],
my_number will be in [start_required , start_required + range_required].
Use QUuid
#include <QUuid>
QString randomStr = QUuid::createUuid();
Works in Qt6
double value= QRandomGenerator::global()->bounded(0, 10);
Generate a double from 0 to 10
Here is the good answer using qrand(). The solution below uses QUuid, as already was suggested above, to generate random and unique ids (they are all hex numbers):
#include <QApplication>
#include <QDebug>
#include <QRegularExpression>
#include <QUuid>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// random hex string generator
for (int i = 0; i < 10; i++)
{
QString str = QUuid::createUuid().toString();
str.remove(QRegularExpression("{|}|-")); // if you want only hex numbers
qDebug() << str;
}
return a.exec();
}
Output
"479a494a852747fe90efe0dc0137d059"
"2cd7e3b404b54fad9154e46c527c368a"
"84e43735eacd4b8f8d733bf642476097"
"d7e824f920874f9d8b4264212f3bd385"
"40b1c6fa89254705801caefdab5edd96"
"b7067852cf9d45ca89dd7af6ffdcdd23"
"9a2e5e6b65c54bea8fb9e7e8e1676a1a"
"981fa826073947e68adc46ddf47e311c"
"129b0ec42aed47d78be4bfe279996990"
"818035b0e83f401d8a56f34122ba7990"

Resources