PDA

View Full Version : byte to uint



#Dragon
22nd October 2015, 18:58
Hi, I'm trying to rewrite some functions from C# to Qt, but something is going wrong. I dont know why...
Could somebody look in my code please ?

Function should convert byte to uint:

Orginal C# function:


public static String ByteToString(byte[] crc)
{
String ret = "";
if(crc != null){
ret = ((int)crc[0]).ToString("X2");
ret += ((int)crc[1]).ToString("X2");
ret += ((int)crc[2]).ToString("X2");
ret += ((int)crc[3]).ToString("X2");
}
return ret;
}

public static uint ByteTouInt(byte[] crc){
if(crc != null) {
return Convert.ToUInt32(Tools.ByteToString(crc), 16);
}else{
return 0;
}
return 0;
}


My function in Qt (First idea)


QString Tools::byteToString(byte *crc)
{
QString crc_string = "";
if(sizeof crc < 4 || crc == NULL) {
return "bad";
}
for(int i = 0; i < 4; i++) {
crc_string += (QString::number((int)crc[i], 16).length() == 1) ? "0" + QString::number((int)crc[i], 16) : QString::number((int)crc[i], 16);
}
return crc_string.toUpper();
}

inline uint byteToUInt(byte *crc) {
return byteToString(crc).toUInt(NULL, 16);
}


Second idea...


inline uint Tools::byteToUInt(byte *b)
{
uint val;
QByteArray ba;
ba.append(((const char*) b));

//val = (ba[1] << 8) | ba[0];
memcpy(&val, ba.constData(), 2);

return val;
}


Function returns different values, I'm not a author of C# code, so I've got problems to convert it properly.
To compile C# code I used this online IDE/compiler: http://www.tutorialspoint.com/compile_csharp_online.php

Thank You for any help and suggestions.

myta212
23rd October 2015, 10:48
Hi Dragon,
Your code convert array of char (4byte) to hex and convert that hex to uint datatype.
This is a simple code how to do that :

#include <QCoreApplication>
#include <QDebug>
#include <stdio.h>

QString ByteToString(uchar *crc)
{
QString ret = "";
QString str;

ret = str.setNum((crc[0]), 16);
ret += str.setNum((crc[1]), 16);
ret += str.setNum((crc[2]), 16);
ret += str.setNum((crc[3]), 16);

return ret;
}

uint ByteTouInt(uchar *crc)
{
if (crc != NULL)
{
bool ok;
return (ByteToString(crc).toUInt(&ok, 16));
}
else
{
return 0;
}
}

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
uchar aa[] = {40,50,60,70};
ByteToString(aa);
uint result = ByteTouInt(aa);
qDebug()<<"Input : " << aa[0]<<aa[1]<<aa[2]<<aa[3];
qDebug()<<"Result : "<< result;
return a.exec();
}


This is the sample result :
Input : 40 50 60 70
Result : 674380870

Please try to read my code to get the algorithm related with your problem.
Hope this code can help you.
Thank you.

#Dragon
27th October 2015, 17:29
Thanks for help :)
Regards