I would like to print the following hashed data. How should I do it?
unsigned char hashedChars[32];
SHA256((const unsigned char*)data.c_str(),
data.length(),
hashedChars);
printf("hashedChars: %X\n", hashedChars); // doesn't seem to work??
The hex format specifier is expecting a single integer value but you're providing instead an array of char. What you need to do is print out the char values individually as hex values.
printf("hashedChars: ");
for (int i = 0; i < 32; i++) {
printf("%x", hashedChars[i]);
}
printf("\n");
Since you are using C++ though you should consider using cout instead of printf (it's more idiomatic for C++.
cout << "hashedChars: ";
for (int i = 0; i < 32; i++) {
cout << hex << hashedChars[i];
}
cout << endl;
In C++
#include <iostream>
#include <iomanip>
unsigned char buf0[] = {4, 85, 250, 206};
for (int i = 0;i < sizeof buf0 / sizeof buf0[0]; i++) {
std::cout << std::setfill('0')
<< std::setw(2)
<< std::uppercase
<< std::hex << (0xFF & buf0[i]) << " ";
}
As mentioned in comments, you need to cast your unsigned char to be recognized as an integral (int or unsigned int since you work with positives values), and you need to add some zeros where the value could be printed by 1 character instead of 2 :
cout << "hashedChars: ";
for (int i = 0; i < 32; i++) {
cout << std::hex << std::setfill('0')
<< std::setw(2) << static_cast<int>(hashedChars[i]);
}
cout << endl;
Related
I am struggling with printing an array with 4 rows and 4 columns, when I initialized the array and entered all the values. Then, I used for loop to get all the values together so I can print them. But I get is an array that companied all the values in one row.
I have attached the output when I run the code.
Here is a portion of my code, it is long code but I am struggling in specific part:
#include <iostream>
using namespace std;
int main()
{
cout << "The martix before I flipped it: " << endl;
cout << endl;
int array[4][4] = { 16,3,2,13,5,10,11,8,9,6,7,12,4,5,14,1 };
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cout << array[i][j] << " ";
}
}
return 0;
The standard output utility std::cout is a stream from the stl and, as such, its << operator does not usually automagically append a linebreak.
Which is quite practical since, otherwise, you would not be able to print multiple numbers on a single line.
That being, said, you'll need to add the linebreak manually, like so :
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
std::cout << array[i][j] << " ";
}
std::cout << std::endl;
}
Alternatively, you can consider printing lines 4 at a time since your matrix is of constant size :
for (int i = 0; i < 4; i++) {
std::cout << array[i][0] << " "
<< array[i][1] << " "
<< array[i][2] << " "
<< array[i][3] << " " << std::endl;
}
Have a great day,
I am trying to write a small program that takes a user-defined string of a limited selection of characters (lowercase letters, parentheses, and the + and * operators), looks at each of the characters, and organizes them into separate arrays. I thought my approach to this exercise would be fairly straightforward, but I have run into some issues that I cannot figure out.
My problem becomes evident when I attempt to print the individual arrays to the screen. If all of the characters are of the same type (for example, "abcd"), the arrays print as intended. But if there is a combination of character types (for example, "(a+b)"), the arrays print incorrectly. I'm ashamed to say I have been banging my head against this (probably obvious) problem for many hours now and cannot seem to figure out what I have done wrong. Any input would be appreciated - I'm not looking for help writing the program, I just want to know what I have done wrong. I have included my code below:
#include <iostream>
#include <string>
using namespace std;
void charOrganizer(int[], char[], char[], char[], int, int&, int&, int&);
int main()
{
//Variable declaration
string userExpression;
int expressionArray[userExpression.length()];
char letterToken[userExpression.length()];
char parenthesesToken[userExpression.length()];
char plusTimesToken[userExpression.length()];
int letterTokenPos = 0;
int parenthesesTokenPos = 0;
int plusTimesTokenPos = 0;
//Prompt user for string input
cout << "Please enter a mathematical expression only using lowercase letters of the \nalphabet, parentheses, and/or the addition/multiplication operators."<< endl;
cin >> userExpression;
int arraySize = userExpression.length();
for (int i = 0; i < arraySize; ++i)
{
expressionArray[i] = userExpression[i];
}
charOrganizer(expressionArray, letterToken, parenthesesToken, plusTimesToken, arraySize, letterTokenPos, parenthesesTokenPos, plusTimesTokenPos);
//Print tokens to screen
cout << "LowerCase Letter Token values in your string:" << endl;
for (int i = 0; i < letterTokenPos; i++)
{
cout << letterToken[i] << endl;
}
cout << "Parentheses Token values in your string:" << endl;
for (int i = 0; i < parenthesesTokenPos; i++)
{
cout << parenthesesToken[i] << endl;
}
cout << "Operator Token values in your string:" << endl;
for (int i = 0; i < plusTimesTokenPos; i++)
{
cout << plusTimesToken[i] << endl;
}
return 0;
}
void charOrganizer (int charValue[], char letArr[], char parArr[], char pluTimArr[], int size, int& letPosition, int&parPosition, int& operPosition)
{
for (int i = 0; i < size; i++)
{
if (charValue[i] > 96 && charValue[i] < 123)
{
letArr[letPosition] = charValue[i];
cout << "Letter Copy Test: " << letArr[letPosition] << endl;
letPosition++;
}
else if (charValue[i] == 40 || charValue[i] == 41)
{
parArr[parPosition] = charValue[i];
cout << "Parentheses Copy Test: " << parArr[parPosition] << endl;
parPosition++;
}
else if (charValue[i] == 42 || charValue[i] == 43)
{
pluTimArr[operPosition] = charValue[i];
cout << "Operator Copy Test: " << pluTimArr[operPosition] << endl;
operPosition++;
}
else
{
cout << "Invalid input" << endl;
}
}
/*cout << "Print Array Test: " << endl;
for (int i = 0; i < letPosition; i++)
{
cout << letArr[i] << endl;
//cout << parArr[i] << endl;
//cout << pluTimArr[i] << endl;
}*/
}
see your below code. You are using the length of a empty string to declare arrays size like below. In this case all the array size will zero size only. Correct it properly:-
//Variable declaration
string userExpression;
int expressionArray[userExpression.length()];// it would be just like int expressionArray[0];
char letterToken[userExpression.length()];
char parenthesesToken[userExpression.length()];
char plusTimesToken[userExpression.length()];
int expressionArray[30];
char letterToken[30];
char parenthesesToken[30];
char plusTimesToken[30];
Else you declare these variables after you enter your string.
I designed a C++ code for checking machine's endian.
It works well. But, it cannot print out each bytes' contents in a 4-byte int.
#include<iostream>
using namespace std;
bool f()
{
int a = 1;
char *p = (char*)&a;
for (int i = 0 ; i < 4 ; ++i)
cout << "p[" << i << "] is " << hex << *p++ << " ";
cout << endl ;
p -= 4;
if (*p == 1) return true ; // it is little endian
else return false; // it is big endian
}
int main()
{
cout << "it is little endian ? " << f() << endl ;
return 0 ;
}
output:
p[0] is p[1] is p[2] is p[3] is
it is little endian ? 1
Why the output is empty ?
thanks
the issue is that the type of *p is char, so the stream attempts to print the value of it as an ASCII character (which is likely not the value of a visible character). If you cast it to an int you will get what you expect:
cout << "p[" << i << "] is " << hex << static_cast<int>(*p++) << " ";
printf suggested is OK but also an alternative is using shift operators <<,>> to investigate individual bytes of the int.
I coded the following to print every byte of an int array. Each int was 4 bytes long.
Hope this helps in some way.
#include <iostream>
#include<math.h>
#include<string.h>
using namespace std;
int main()
{
int length = 5;
unsigned int* array = new unsigned int[length];
for(int i=0; i<length; i++)
array[i] = 16843009;
for(int i=0;i<=4;i++)
{
int new_dividend=0,k=0,l=0;
double bytevalue=0;
int bits[32];
int number=array[i];
//Initializing
for(int c=0;c<=31;c++)
{
bits[c]=0;
}
//convert to binary
while(number!=1)
{
new_dividend=number/2;
bits[k]=number%2;
number=new_dividend;
k++;
}
bits[k]=1;
//Pad with zero if needed
if(k!=31)
{
for(int ctr=k+1;ctr<=31;ctr++)
{
bits[ctr]=0;
}
}
for(int counter=0;counter<=31;counter++)
{
//Print value of each byte.Also Reset values after each bytevalue has been printed.
if(l==8)
{
l=0;
cout<<bytevalue;
bytevalue=0;
}
//calculate value of each byte
bytevalue=bytevalue+(pow(double(2),l))*bits[counter];
++l;
}
if(l==8)
{cout<<bytevalue;
}
}
delete[] array;
return 0;
}
Expected Output = 11111111111111111111 for an array[i] = 16843009 where i may be any range.
Please assist, I am trying to format a phone number like (111)111-1111. I have the following code which works but I would like to write much shorter.
int main(){
string phone_number;
cin >> phone_number;
cout<<"(";
for(int i = 0; i < 3; i++) {
cout << phone_number[i];
}
cout << ")";
for(int i = 3; i < 6; i++) {
cout << phone_number[i];
}
cout << "-";
for(int i = 6; i < 10; i++) {
cout << phone_number[i];
}
cout<<endl;
return 0;
}
please assist
Another possibility:
cout << "(" << phone_number.substr(0,3) << ")"
<< phone_number.substr(3,3) << "-" << phone_number.substr(6,4) << endl;
Use string::insert. But since you are taking a string as input, why wouldn't you give the input in format you need. Any how, this is how it can be done with out any loops if you wish to modify the string. In case you don't wish to change the original string then store the modified to a different temporary variable.
string phone_number = "123456789";
phone_number = phone_number.insert( 0, "(" ); // Original string is modified
// Rest can be achieved in similar fashion
cout << phone_number << endl;
for (int i=0; i<10; ++i)
{
if (i == 0) std::cout << '(';
else if (i == 3) std::cout << ')';
else if (i == 6) std::cout << '-';
std::cout << phone_number[i];
}
Probably wouldn't be good to change your data just to format.
string str(phn);
// Format Phone# 1: void function
printf("(%s)%s-%s",
str.substr(0,3).c_str(),
str.substr(3,3).c_str(),
str.substr(6, 4).c_str());
// Format Phone# 2: returns std::string&
stringstream p;
p << "(" << str.substr(0, 3) << ")"
<< str.substr(3, 3) << "-"
<< str.substr(6, 4);
return p.str();
Ignoring the question as to why you want to write this "shorter" ...
printf("(%c%c%c)%c%c%c-%c%c%c%c\n", phone_number[0], phone_number[1], phone_number[2],
phone_number[3], phone_number[4], phone_number[5],
phone_number[6], phone_number[7], phone_number[8],
phone_number[9]);
That being said - your code (nor this) checks to see if there's actually 10 numbers present, or if they're numbers at all. That above all is more important than wanting it "shorter".
Your code is too short, not too long. Any input from the user must always be checked for validity. For instance, what if the used already entered the punctuation, so that phone_number contains "(111)111-1111"? Then your code would output "((11)-)11-1-11" (I think). This is not what you want. At the very least, you must throw out all non-digit characters.
#include <iostream>
using namespace std;
int main(){
string phone_number;
cin >> phone_number;
cout<<"(";
for(int i = 0; i < 3; i++) {
cout << phone_number[i];
}
cout << ")";
for(int i = 3; i < 6; i++) {
cout << phone_number[i];
}
cout << "-";
for(int i = 6; i < 10; i++) {
cout << phone_number[i];
}
cout<<endl;
return 0;
}
I have a serious and irritating problem, please help
mdContext->digest[i] is an unsigned char Array with hexadecimal values so
for (i = 0; i < 16; i++)
printf ("%02x", mdContext->digest[i]);
prints 900150983cd24fb0d6963f7d28e17f72
now.... I want to get this value in a char Array, i.e if I do
printf("%s",ArrayConverted);
I want to print the above string... Please help me in doing this
Things I tried
Trial-1
unsigned char in[64]=0;
int tempValue[64];
for (i = 0; i < 16; i++){
sprintf(&tempValue[i],"%02x", (unsigned char)mdContext->digest[i]);
in[i]=(unsigned char)tempValue[i];
}
printf("%s\n\n\n",in);
This prints
90593d4bd9372e77 But Original content is 900150983cd24fb0d6963f7d28e17f72
So it is skipping many characters in between... please help me converting this hexadecimal Char array in to a String
char tempValue[33]; // 32 hex digits + 0-terminator
int i;
for (i = 0; i < 16; ++i)
sprintf(tempValue + 2*i, "%02x", (unsigned char)mdContext->digest[i]);
Each byte requires two hexadecimal digits - so adjust the start position for sprintf with 2*i
tempValue + 2*i is the same as &tempValue[2*i]
EDIT: A correct c++ version.
std::stringstream s;
for (int i = 0; i < 16; ++i)
s << std::hex << std::setfill('0') << std::setw(2) << (unsigned short) mdContext->digest[i];
std::cout << s.str() << std::endl;
C++ specific solution:
#include <sstream>
#include <iomanip>
std::stringstream s;
s.fill('0');
for ( size_t i = 0 ; i < 16 ; ++i )
s << std::setw(2) << std::hex <<(unsigned short)mdContext->digest[i]);
std::cout << s.str() << endl;
Small demo : http://ideone.com/sTiEn