This question already has an answer here:
convert byte[] to string when upload a file in asp.net
(1 answer)
Closed 8 years ago.
I have a byte[] and want to convert it to string in asp.net.
Here is my code:
for (int loop1 = 0; loop1 < size; loop1++)
{
displayString = displayString + input[loop1].ToString();
}
But this code takes too long, is there another solution?
Just use the Encoding.GetString method. This will do all the work for you:
string s = Encoding.UTF8.GetString(input);
Make sure the encoding you use is the correct one for the string array. See the MSDN reference of the Encoding class to see all the encodings available.
Related
Below is the code snippet:
I am trying to upload a file having long as a datatype and storing that file size in a byte array.
long fileSize = uploadedFile.getSize();
byte techGuide[] = new byte[fileSize];
I got the build error:
error: incompatible types: possible lossy conversion from long to int
Please suggest what i am missing and what should i try?
Path path = uploadedFile.toPath(); // File.toPath.
Repair of your code:
// Not needed for readAllBytes.
long fileSize = Files.size(path);
if (fileSize > Integer.MAX) {
throw new IllegalArgumentException("File too large");
}
byte[] techGuide = new byte[(int)fileSize];
New code:
byte[] techGuide = Files.readAllBytes(path);
Arrays are limited by their int index. You would need to cast the fileSize to an int (and check an overflow). However Files.readAllBytes does that for you, throwing an OutOfMemoryError of > Integer.MAX - 8.
The following test fails on Java 9 while passes in Java 8:
#Test
public void getImage_SetValueUsingConstructor_ShouldReturnCorrectValue() throws Exception {
String base64ImageString = "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAEUlEQVR42mNgQAP/wQAbBw4ANwsL9Zo6V30AAAAASUVORK5CYII=";
byte[] rawImageBytes = Base64.getDecoder().decode(base64ImageString);
ByteArrayInputStream bis = new ByteArrayInputStream(rawImageBytes);
RenderedImage image = ImageIO.read(bis);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(image, "PNG", bos);
byte[] imageBytesFromImage = bos.toByteArray();
assertArrayEquals(imageBytesFromImage, rawImageBytes);
}
Java 9 output:
arrays first differed at element [42];
Expected :94
Actual :-38
Can anyone help me understand what was changed in Java 9, and is there a way to write this code so that it will work for both Java 8 & 9?
As #Holger has pointed out in the comments, it is really the test that is flawed. While identical Base64 representations will give identical images, different Base64 representations does not mean the image data is different. It could mean only that the same image data is encoded differently, and will decode to the exact same image (which is the case here).
The reason your test used to pass without error, is probably that you used the Java 8 PNGImageWriter (or earlier, it hasn't really changed much since Java 1.4), which is the writer plugin used if you do ImageIO.write(image, "PNG", output), to encode the image and created the Base64 representation from it. If you had created the Base64 representation of the bytes from a file created by a different program/library, it would almost certainly be different.
You should rewrite your test, it is however not really clear to me what you are trying to test here.
If you only care about pixel data, you could just loop over the pixels and test for equality:
BufferedImage original = ImageIO.read(..);
BufferedImage current = ImageIO.read(..);
assertEquals(original.getWidth(), current.getWidth());
assertEquals(original.getHeight(), current.getHeight());
for (int y = 0; y < original.getHeight(); y++) {
for (int x = 0; x < original.getWidth(); x++) {
assertEquals(original.getRGB(x, y), current.getRGB(x, y));
}
}
If you also need the metadata to be preserved, you also need to test for equality there. But PNG doesn't really contain much interesting metadata, so I doubt you need that.
Thanks to Holger for the comments, what I did is to decode an image from the byte array and then compare the dataBuffer of both images.
The test below passed on both Java 8 and
#Test
public void imageTest() throws Exception {
String base64ImageString = "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAEUlEQVR42mNgQAP/wQAbBw4ANwsL9Zo6V30AAAAASUVORK5CYII=";
byte[] rawImageBytes = Base64.getDecoder().decode(base64ImageString);
ByteArrayInputStream bis = new ByteArrayInputStream(rawImageBytes);
RenderedImage image = ImageIO.read(bis);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(image, "PNG", bos);
byte[] imageBytesFromImage = bos.toByteArray();
//assertArrayEquals(imageBytesFromImage, rawImageBytes); //fails on Java 9!
bis = new ByteArrayInputStream(imageBytesFromImage);
RenderedImage image2 = ImageIO.read(bis);
DataBuffer dbA = image.getData().getDataBuffer();
int sizeA = dbA.getSize();
DataBuffer dbB = image2.getData().getDataBuffer();
int sizeB = dbB.getSize();
// compare data-buffer objects //
assertEquals(sizeA, sizeB);
for (int i = 0; i < sizeA; i++) {
assertEquals(dbA.getElem(i), dbB.getElem(i));
}
}
The compare images code was taken from: How to compare images for similarity using java
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
Jasoos (Cryptography Algorithm)
I am working on encrypting and decrypt web application. I have built an algorithm that uses 24-byte key to encrypt/decrypt the message.
Review this algorithm and please suggest anything important and fault in this algorithm that can make it perform better. Your contribution can help us to improve our algorithm.
Code is provided on my GitHub
Algorithm:-
1] 24 digit entered/generated key will be converted into ASCII code of 24 digit code.
public void setKey(char[] arr){
for(int i=0;i<24;i++){
key[i] = (int)arr[i];
}
}
2] Entered String will be changed into a character array.
Every character will be then incremented first with the key’s value and changed into 10-bit binary code.
public void Encryption(String text){
char[] msg = text.toCharArray();
int flag = 0;
int l = msg.length;
for(int i=0;i<l;i++){
int a = (int)msg[i];
// System.out.print(msg[i]+" "+a+"-> ");
if(flag>23)
flag=0;
int b=a+key[flag];
flag++;
//System.out.print(b+" | ");
String z = binary(b);
sb.append(lookUpTool(z));
//Character.toString((char)b);
}
//sb.append(sumBinary);
sb = comp1(sb);
}
3] lookUp(): - It will take a 10-bit string as input and a matrix, and divide that string into two 5 bit binary code.
We will then calculate decimal value of each 5-bit binary code.
Example: 0011101101 -> 00111 = 7 and 01101 = 13
We have a matrix of 32 X 32 dimensions which has unique random values from 0 to 1023 and will not be shared publicly.
For 0011101101 we will look for 7th row and 13th column value.
That value will be changed into 10 bits binary code.
public String lookUp(String bits, int[][] mat){
int mid = Math.round((float) bits.length() / 2);
String part1 = bits.substring(0, mid);
String part2 = bits.substring(mid, bits.length());
int row=binaryValue(part1);
int col=binaryValue(part2);;
//System.out.print("row: "+row);
// System.out.println("|| col: "+col);
int a = mat[row][col];
return binary(a);
}
4] We will perform this steps ten times with ten different private matrices by lookUpTool method.
public String lookUpTool(String s){
String s1 = lookUp(s,matrix1);
String s2 = lookUp(s1,matrix2);
String s3 = lookUp(s2,matrix3);
String s4 = lookUp(s3,matrix4);
String s5 = lookUp(s4,matrix5);
String s6 = lookUp(s5,matrix6);
String s7 = lookUp(s6,matrix7);
String s8 = lookUp(s7,matrix8);
String s9 = lookUp(s8,matrix9);
String s10 = lookUp(s9,matrix10);
return s10;
}
Similarly, we will do this for each character in the text/string and encrypt it.
Example:-
Key: c|H#yLzd3PkRte0H,u16zt8N
Message: abcd ef$
After Encryption: 11001111000001101010000010000101101000001110100000101010111001110000011000001000
Your algorithm is completely worthless by any reasonable standard. The most obvious problem is this:
You just gave us a key, plaintext, and corresponding encoded message. This leaks out numerous entries from your super-secret matrix that you weren't supposed to share publicly. (Each ten-bit chunk of the encrypted message is an entry from that array, and with the key and plaintext, I can figure out which one it is.)
Imagine if an adversary had a collection of messages that were already encrypted by your algorithm and then you posted this challenge. He can now decrypt a significant fraction of those messages, just from what you leaked in this challenge. And if there are obvious missing bits, say he has "trans_ormer", he can work out another entry in your formerly super-secret array.
But please read the links in the comments. Trying to design your own encryption algorithm for actual use and reliance in this way is absolutely foolish. A new algorithm cannot even be considered for actual use before it has been reviewed thoroughly by experts in each type of known cryptanalysis.
Another algorithmic flaw is immediately obvious. An attacker will know that the key repeats every 24 characters. With a long enough message, say in English, the attacker can do a frequency analysis for each set of every 24th character. It's even worse if the attacker knows the message format and that format has an even more unequal frequency distribution.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am creating a GUI for windows PC. I want to store a series of images on the PC. The name of the images is identical. But I want to append them with timestamps. So, how to save image using timestamp in Qt?
in addition to that, the images shud be saved something like this example:
referenceImage<.date.><.time.>jpg
where date and time correspond to the date on and time at which the image was saved on the windows PC. I have tried the following too
Here i have implemented this at the click of a push button:-
void MainWindow::on_generateImagePushButton_clicked()
{
QDate date = QDate::currentDate();
QString dateString = date.toString();
QString path = QString("E:\\QT1\\timeStampTrial\\goldenRefImg[%1].jpg").arg(dateString);
qDebug()<<"path: "<<path;
/*display current time*/
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString path2 = QString("E:\\QT1\\timeStampTrial\\goldenRefImg[%1 %2].jpg").arg(dateString).arg(timeString);
qDebug()<<"path2: "<<path2;
/*converting from QString to char* */
QByteArray bA = path2.toLocal8Bit();
const char *c_charArray = bA.data();
/*saving image*/
IplImage *imgWithTimeStamp = cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3);
cvSaveImage(c_charArray, imgWithTimeStamp);
}
The image gets saved with dateStamp, ie eg. goldenRefImg[Wed Feb 5 2014].jpg when I use string-path. But when I use string-path2, it does NOT save with dateStamp & timeStamp as i expect it to, i.e. goldenRefImg[Wed Feb 5 2014 10:47:32].jpg
But the qDebug statements showing path and path2 are displayed correctly.
Application Output:
Starting E:\QT1\timepass-build-desktop-Qt_4_8_1_for_Desktop_-_MSVC2010__Qt_SDK__Debug\debug\timepass.exe...
path: "E:\QT1\timeStampTrial\goldenRefImg[Wed Feb 5 2014].jpg"
path2: "E:\QT1\timeStampTrial\goldenRefImg[Wed Feb 5 2014 10:47:23].jpg"
Now i have just recollected that an image cannot be saved with special characters such as the colon : which's there in timeStamp. Can the time format be changed?
I tried this way:
path2.replace(":","-");
But the E:\ also gets converted into E-.Please guide. Thank u.
const QDateTime now = QDateTime::currentDateTime();
const QString timestamp = now.toString(QLatin1String("yyyyMMdd-hhmmsszzz"));
const QString filename = QString::fromLatin1("/some/path/someimage-%1.jpg").arg(timestamp);
This takes the current date/time, converts it to a string using QDateTime::toString() (the documentation lists the formatting options) and constructs the file name out of it.
Then just use filename with QImage::save() or QImageWriter.
/*display current date*/
QDate date = QDate::currentDate();
QString dateString = date.toString();
QString path = QString("E:\\QT1\\timeStampTrial\\goldenRefImg[%1].jpg").arg(dateString);
qDebug()<<"path: "<<path;
/*display current time*/
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString path2 = QString("E:\\QT1\\timeStampTrial\\goldenRefImg[%1 %2].jpg").arg(dateString).arg(timeString);
qDebug()<<"path2: "<<path2;
path2.replace(":","-");
path2.replace(1,1,":");
QByteArray bA = path2.toLocal8Bit();
const char *c_charArray = bA.data();
IplImage *imgWithTimeStamp = cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3);
cvSaveImage(c_charArray, imgWithTimeStamp);
Thank you for all your suggestions #Dmitri Sazonov and #Frank Osterfeld
I'm working with Qt on an existing project. I'm trying to send a string over a serial cable to a thermostat to send it a command. I need to make sure the string only contains 0-9, a-f, and is no more or less than 6 characters long. I was trying to use QString.contains, but I'm am currently stuck. Any help would be appreciated.
You have two options:
Use QRegExp
Use the QRegExp class to create a regular expression that finds what you're looking for. In your case, something like the following might do the trick:
QRegExp hexMatcher("^[0-9A-F]{6}$", Qt::CaseInsensitive);
if (hexMatcher.exactMatch(someString))
{
// Found hex string of length 6.
}
Update
Qt 5 users should consider using QRegularExpression instead of QRegExp:
QRegularExpression hexMatcher("^[0-9A-F]{6}$",
QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = hexMatcher.match(someString);
if (match.hasMatch())
{
// Found hex string of length 6.
}
Use QString Only
Check the length of the string and then check to see that you can convert it to an integer successfully (using a base 16 conversion):
bool conversionOk = false;
int value = myString.toInt(&conversionOk, 16);
if (conversionOk && myString.length() == 6)
{
// Found hex string of length 6.
}