How convert QChar to char code in cp866 table? - qt

How get int code of qchar in this table http://www.ascii-codes.com/cp866.html ?
Here is my code:
int getCp866Code(QChar c) {
if (!c.isSurrogate()) {
QString temp = c;
QTextCodec* cp866 = QTextCodec::codecForName("IBM 866");
QByteArray byteArray = cp866->fromUnicode(temp);
return (int) byteArray[0];
}
return -1;
}
getCp866Code('ж') // returns -90, not 166

The question is ill posed. QChar is a UTF-16 code unit (which also means it can be part of a surrogate pair). Your best shot would be
Check that it's not part of a surrogate pair (QChar::isSurrogate)
Build a QString consisting only of that char, then use QTextCodec to encode the string in CP866. Then extract the first byte of it.
Note that it's unspecified what you get if your code point is not encodeable in CP866.

Related

Convert String to Char* and Hash It using SHA-256

I'm trying to concatenate the current DateTime to my devices Mac Address in the following format: aa:bb:cc:dd:ee:ffYYmmDDhhMMss so I can hash it and send it to a web service every time I collect new data (so I'll have to hash it in every loop)
I managed to concatenate the two values (mac address + datetime) and converted it to char array
addressDateTime.toCharArray(thisThing, 28);
However, I'm kind of lost as to how to continue.
I've also tried to read the resulting char* with this cycle but I'm not understanding why it doesn't work:
void loop() {
while (!timeClient.update()) {
timeClient.forceUpdate();
}
String addressDateTime = getPayload(); //this gets the *aa:bb:cc:dd:ee:ffYYmmDDhhMMss* string
char* hashThis;
addressDateTime.toCharArray(hashThis, 28);
for (int i = 0; i < sizeof(hashThis); i++) {
char str[3];
sprintf(str, "%02x", hashThis[i]);
Serial.print(str);
}
delay(5000);
}
Am I converting the String to char* correctly?
How should I go about Hashing the char*?
Or can I Hash the String without converting it to to char*?
Update:
My code's looking like this atm
while (!timeClient.update()) {
timeClient.forceUpdate();
}
String addressDateTime = getPayload();
char hashThis[30];
addressDateTime.toCharArray(hashThis, 30);
for (int i = 0; i < sizeof(hashThis); i++) {
Serial.printf("%02x", hashThis[i]);
}
delay(5000);
}
So I managed to convert the String to Char* Except that the output is looking like this 33433a37313a42463a31443a34323a463431393035303531343038323700 instead of (for example) aa:bb:cc:dd:ee:ff190505141037
After figuring out why my char* array outputs like that I still have to hash it.
Thanks for helping me get this far, I still have ways to go
You're not allocating space to store the C string that you're getting from addressDateTime.
hashThis is a char* which is a pointer to a character. It hasn't been set to anything so it's just... random. Which will almost certainly make your program crash or at least misbehave badly.
Given your code, the quickest fix is to change
char* hashThis;
to
char hasThis[30];
addressDateTime.toCharArray(hashThis, 30);
I changed 28 to 30 because aa:bb:cc:dd:ee:ffYYmmDDhhMMss is actually 29 characters long and also requires an extra byte for the C string null terminator character. I'm not 100% sure if the toCharArray() method sets the null terminator; if it doesn't, you'd need to add
hasThis[29] = '\0';
You can avoid that by just using the String c_str() method, which returns a char* to the internal buffer that String uses to hold the string.
In that case you could rewrite
char* hashThis;
addressDateTime.toCharArray(hashThis, 28);
as
char* hashThis = addressDateTime.c_str();
By the way, you can also just do
Serial.printf("%02x", hashThis[i]);
and dispense with the snprintf(). Kudos on getting the right buffer size there, though!
UPDATE
In your updated question, you said that you're expecting to see output that looks like:
aa:bb:cc:dd:ee:ff190505141037
instead of:
33433a37313a42463a31443a34323a463431393035303531343038323700
Your code is
for (int i = 0; i < sizeof(hashThis); i++) {
Serial.printf("%02x", hashThis[i]);
}
You're writing each character as a two digit hexadecimal number, so you're going to see the number in hexadecimal that represents the character, not the character itself. If you want to see the characters, do:
for (int i = 0; i < strlen(hashThis); i++) {
Serial.printf("%c", hashThis[i]);
}
or (better)
for (int i = 0; i < strlen(hashThis); i++) {
Serial.print(hashThis[i]);
}
or (best)
Serial.println(hashThis);
Note that I changed your sizeof to a strlen. If for some reason you put a shorter string in hashThis, strlen will do the right thing whereas sizeof will always return the length that hashThis was declared with rather than the length of the string in it.

QString to unicode std::string

I know there is plenty of information about converting QString to char*, but I still need some clarification in this question.
Qt provides QTextCodecs to convert QString (which internally stores characters in unicode) to QByteArray, allowing me to retrieve char* which represents the string in some non-unicode encoding. But what should I do when I want to get a unicode QByteArray?
QTextCodec* codec = QTextCodec::codecForName("UTF-8");
QString qstr = codec->toUnicode("Юникод");
std::string stdstr(reinterpret_cast<const char*>(qstr.constData()), qstr.size() * 2 ); // * 2 since unicode character is twice longer than char
qDebug() << QString(reinterpret_cast<const QChar*>(stdstr.c_str()), stdstr.size() / 2); // same
The above code prints "Юникод" as I've expected. But I'd like to know if that is the right way to get to the unicode char* of the QString. In particular, reinterpret_casts and size arithmetics in this technique looks pretty ugly.
The below applies to Qt 5. Qt 4's behavior was different and, in practice, broken.
You need to choose:
Whether you want the 8-bit wide std::string or 16-bit wide std::wstring, or some other type.
What encoding is desired in your target string?
Internally, QString stores UTF-16 encoded data, so any Unicode code point may be represented in one or two QChars.
Common cases:
Locally encoded 8-bit std::string (as in: system locale):
std::string(str.toLocal8Bit().constData())
UTF-8 encoded 8-bit std::string:
str.toStdString()
This is equivalent to:
std::string(str.toUtf8().constData())
UTF-16 or UCS-4 encoded std::wstring, 16- or 32 bits wide, respectively. The selection of 16- vs. 32-bit encoding is done by Qt to match the platform's width of wchar_t.
str.toStdWString()
U16 or U32 strings of C++11 - from Qt 5.5 onwards:
str.toStdU16String()
str.toStdU32String()
UTF-16 encoded 16-bit std::u16string - this hack is only needed up to Qt 5.4:
std::u16string(reinterpret_cast<const char16_t*>(str.constData()))
This encoding does not include byte order marks (BOMs).
It's easy to prepend BOMs to the QString itself before converting it:
QString src = ...;
src.prepend(QChar::ByteOrderMark);
#if QT_VERSION < QT_VERSION_CHECK(5,5,0)
auto dst = std::u16string{reinterpret_cast<const char16_t*>(src.constData()),
src.size()};
#else
auto dst = src.toStdU16String();
If you expect the strings to be large, you can skip one copy:
const QString src = ...;
std::u16string dst;
dst.reserve(src.size() + 2); // BOM + termination
dst.append(char16_t(QChar::ByteOrderMark));
dst.append(reinterpret_cast<const char16_t*>(src.constData()),
src.size()+1);
In both cases, dst is now portable to systems with either endianness.
Use this:
QString Widen(const std::string &stdStr)
{
return QString::fromUtf8(stdStr.data(), stdStr.size());
}
std::string Narrow(const QString &qtStr)
{
QByteArray utf8 = qtStr.toUtf8();
return std::string(utf8.data(), utf8.size());
}
In all cases you should have utf8 in std::string.
You can get the QByteArray from a UTF-16 encoded QString using this:
QTextCodec *codec = QTextCodec::codecForName("UTF-16");
QTextEncoder *encoderWithoutBom = codec->makeEncoder( QTextCodec::IgnoreHeader );
QByteArray array = encoderWithoutBom->fromUnicode( str );
This way you ignore the unicode byte order mark (BOM) at the beginning.
You can convert it to char * like:
int dataSize=array.size();
char * data= new char[dataSize];
for(int i=0;i<dataSize;i++)
{
data[i]=array[i];
}
Or simply:
char *data = array.data();

convert std::ostream to some array?

I have a legacy library that takes data from hardware and writes it to ostream.
The method looks like following :
int sensors(ostream*) const;
I am not skilled enough in Ancient Ways. How to convert this data to QByteArray? Or, at least, to char array of known size?
I would have solved it myself, but there is an additional problem: the data in ostream seem to be arbitrary length and have several arbitrary '\0' symbols, so you can't count on it being null-terminated.
I think this is what OrcunC was getting at:
std::stringstream s;
sensors( &s );
QByteArray( s.str().data(), (int) s.str().size() );
... but hopefully more clear :). See also std::stringstream and std::string for information on the classes/member functions used here. By the way, note that I am using str().data(), not str().c_str() -- I'm being really careful to handle those \0 characters, and I'm not assuming NULL termination.
I have not tried it, but you need something like this :
ostream s (ios::out | ios::binary);
//..Populate the stream
//Convert it to string. string can hold \0 values too.
string str = s.str ();
QByteArray ba (str.data (),str.size ());
You can subclass std::ostream and use an object of the subclass to collect the bytes into your QByteArray.
/**
* This helper class collects bytes that are passed to it
* into a QByteArray.
*
* After https://stackoverflow.com/a/19933011/316578
*/
class QByteArrayAppender : public std::ostream, public std::streambuf {
private:
QByteArray &m_byteArray;
public:
QByteArrayAppender(QByteArray &byteArray)
: std::ostream(this),
std::streambuf(),
m_byteArray(byteArray) {
}
int overflow(int c) {
m_byteArray.append(static_cast<char>(c));
return 0;
}
};
This avoids going via an std::string, which is an extra copy of the byte array.

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"

QByteArray to integer

As you may have figured out from the title, I'm having problems converting a QByteArray to an integer.
QByteArray buffer = server->read(8192);
QByteArray q_size = buffer.mid(0, 2);
int size = q_size.toInt();
However, size is 0. The buffer doesn't receive any ASCII character and I believe the toInt() function won't work if it's not an ASCII character. The int size should be 37 (0x25), but - as I have said - it's 0.
The q_size is 0x2500 (or the other endianness order - 0x0025).
What's the problem here ? I'm pretty sure q_size holds the data I need.
Something like this should work, using a data stream to read from the buffer:
QDataStream ds(buffer);
short size; // Since the size you're trying to read appears to be 2 bytes
ds >> size;
// You can continue reading more data from the stream here
The toInt method parses a int if the QByteArray contains a string with digits. You want to interpret the raw bits as an integer. I don't think there is a method for that in QByteArray, so you'll have to construct the value yourself from the single bytes. Probably something like this will work:
int size = (static_cast<unsigned int>(q_size[0]) & 0xFF) << 8
+ (static_cast<unsigned int>(q_size[1]) & 0xFF);
(Or the other way around, depending on Endianness)
I haven't tried this myself to see if it works but it looks from the Qt docs like you want a QDataStream. This supports extracting all the basic C++ types and can be created wth a QByteArray as input.
bool ok;
q_size.toHex().toInt(&ok, 16);
works for me
I had great problems in converting serial data (QByteArray) to integer which was meant to be used as the value for a Progress Bar, but solved it in a very simple way:
QByteArray data = serial->readall();
QString data2 = tr(data); //converted the byte array to a string
ui->QProgressBar->setValue(data2.toUInt()); //converted the string to an unmarked integer..
This works for me:
QByteArray array2;
array2.reserve(4);
array2[0] = data[1];
array2[1] = data[2];
array2[2] = data[3];
array2[3] = data[4];
memcpy(&blockSize, array2, sizeof(int));
data is a qbytearray, from index = 1 to 4 are array integer.
Create a QDataStream that operates on your QByteArray. Documentation is here
Try toInt(bool *ok = Q_NULLPTR, int base = 10) const method of QByteArray Class.
QByteArray Documentatio: http://doc.qt.io/qt-5/QByteArray.html

Resources