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
Related
I am trying to do my assignment for CS, but I can not find how to get a string's first character.
Example input : 5ABCD1AB1AD
Desired output: 5
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
string word;
word = argv[1];
cout << "Word: " << word << "\n";
int length = word[0];
cout << "Word's length : " << length << "\n";
for(int i = 1; i < argc; i++){
for(int j = 0; j < length; j++){
cout << argv[i][j] << "\n";
}
}
}
word[0] is a character. There is a difference between the character '5' and the number 5. If you assign a character to an int you will get the encoding value for that character.
To convert a character to its numeric value you can subtract '0', since the encoding values for the digits are consecutive.
int length = word[0] - '0';
I have a task like this:
The user enters the numbers N1(str1) and N2(str2) in hexadecimal. The program must convert the numbers from hexadecimal to a system of 2 ^ 16 and count the sum of the numbers N1 and N2 in the 2^16 system, then translate the result into a hexadecimal system.
I had such an idea:
first convert from hexadecimal to decimal (I can do this).
Then take each number modulo 2 ^ 16 the logarithm of the base 2 ^ 16 of the number N1dec(dec11) (or N2dec(dec22)) times and write the remainders in the corresponding arrays. This is where my problems began. My conversion from decimal to 2^16 system does not work. Hope You can help.
#include <iostream>
using namespace std;
int main()
{
//HEX to decimal
const char* const str1 = "101D0";//7A120 = 500000; 101D0 = 66000; //1F4 = 500=dec1=N1
cout << "Hello!\nFirst number in HEX system is " << str1 << endl;
istringstream is(str1);
int dec1;
is >> hex >> dec1;
if (!is && !is.eof()) throw "dammit!";
cout << "First number in decimal system: " << dec1 << endl;
const char* const str2 = "1567";//5479=dec2=num2
cout << "Second number in HEX system is " << str2 << endl;
istringstream iss(str2);
int dec2;
iss >> hex >> dec2;
if (!iss && !iss.eof()) throw "dammit!";
cout << "Second number in decimal system: " << dec2 << endl;
//
//Decimal to 2^16 system
int dec11 = dec1;//because dec11 will be = 0
int dec22 = dec2;//because dec22 will be = 0
int k = 1 << 16;
cout << "2^16 = " << k << endl;
int intPART1 = log(dec11) / log(k);
cout << "Int part of log2^16 (" << dec11 << ") is " << intPART1 << endl << "So num1 in 2^16 system will look like ";
int *n1 = new int[intPART1 + 1];
for (int i = 0; i <= intPART1; i++)
{
if (i != 0)
{
n1[i] = dec11 % k*(1<<16-1);
dec11 = dec11 / k;
}
else
{
n1[i] = dec11 % k;
dec11 = dec11 / k;
}
}
for (int i = intPART1; i >= 0; i--)
{
cout << n1[i] << " ";
}
cout << endl;
int intPART2 = log(dec22) / log(k);
cout << "Int part of log2^16 (" << dec22 << ") is " << intPART2 << endl << "So num2 in 2^16 system will look like ";
int *n2 = new int[intPART2 + 1];
for (int i = 0; i <= intPART2; i++)
{
if (i != 0)
{
n2[i] = dec22 % k*(1 << 16 - 1);
dec22 = dec22 / k;
}
else
{
n2[i] = dec22 % k;
dec22 = dec22 / k;
}
}
for (int i = intPART2; i >= 0; i--)
{
cout << n2[i] << " ";
}
cout << endl;
Since hexadecimal values are of base 16, let us say 16^1 and base 2^16 can be recalculated to 16^4 we can already see that your target base is a multiple of your source base. This makes the computation pretty easy and straight forward. All we have to do is some bit shifiting.
int hexToInt(char c)
{
if (c >= 'a')
return c - 'a' + 10;
if (c >= 'A')
return c - 'A' + 10;
return c - '0';
}
// Converts hex to base 2^16. vector[0] holds the MSB.
std::vector<unsigned short> toBase0x10000(std::string const& hex)
{
std::size_t bufSize = hex.size() / 4 + (hex.size() % 4 > 0);
std::vector<unsigned short> number(bufSize);
int shift = 0;
int value = 0;
std::size_t numIndex = number.size();
for (int i = hex.size() - 1; i >= 0; i--)
{
value |= hexToInt(hex[i]) << shift;
shift += 4;
if (shift == 16)
{
number[--numIndex] = static_cast<unsigned short>(value);
shift = 0;
value = 0;
}
}
if (value != 0)
number[--numIndex] = static_cast<unsigned short>(value);
return number;
}
std::string fromBase0x10000(std::vector<unsigned short> const& num)
{
std::stringstream ss;
for (auto&& digit : num)
ss << std::hex << digit;
return ss.str();
}
toBase0x10000 returns a std::vector<unsigned short> so each element in the vector represents one digit of your base 2^16 number (since unsigned short can hold exaclty that value range).
As a side effect this implementation supports any precision number so you are not limited by the value range of numeric types like int or long.
Here is a full example.
Since this looks like a learning exercise you want to solve yourself, here are two hints.
A hex digit represents four bits, so each base-65,536 digit consists of four hex digits. You can therefore read the digits in groups of four, with no need to convert to or from decimal. The same algorithm you learned to decode four decimal digits will work for hex, except the multiplications will be even more efficient because the compiler will optimize them into left-shift instructions.
You should use the uint16_t type from <stdint.h> for this arithmetic, as it it is exactly the right size and unsigned. Unsigned arithmetic overflow is defined as wrapping around, which is what you want. Signed overflow is undefined behavior. (Or #include <cstdint> followed by using std::uint16_t; if you prefer.)
To add digits in any base b, take the sum of the digits modulo b. This will be even easier when b is a power of 2, because the x86 and many other CPUs have a 16-bit unsigned add instruction that does this in hardware, and on any machine that doesn’t, the compiler can optimize this to the bitmask & 0xFFFFU.
In both cases, you can, if you want, write out the binary optimizations by hand using << and & rather than * and %. This might even improve the generated code, slightly, if you use signed rather than unsigned math. However, any modern compiler is smart enough to perform this kind of micro-optimization for you. You are better off not optimizing prematurely, and writing code that is easier to read and understand.
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.
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;
If I have these code:
unsigned char **keys;
int *num_keys;
int num_images = (int) key_files.size(); // the result is 10 for example
keys = new unsigned char *[num_images];
num_keys = new int[num_images];
/* Read all keys */
for (int i = 0; i < num_images; i++) {
keys[i] = NULL;
num_keys[i] = ReadKeyFile(key_files[i].c_str(), keys+i);
}
I would like to read back using printf all of the elements inside keys, how can I do it?
I am just starting with C++, pointers make me not comfortable.
For other language, I think it should be an array of 2 dimensions: array[a][b] then I can loop it like this:
for(int i=0; i<a; i++)
for(int i=j; j<b; j++)
printf(array[i][j]);
I think something like that, unless the char **keys has another meaning? and how can I print all of them?
Thanks in advance.
In C++, your program could be written like this:
#include <vector>
#include <iostream>
//...
const unsigned int num_images = key_file.size();
std::vector<unsigned char *> keys(num_images);
std::vector<int> num_keys(num_images);
for (std::size_t i = 0; i != num_images; ++i)
{
num_keys[i] = ReadKeyFile(key_files[i].c_str(), &keys[i]);
// if the key is a null-terminated string:
std::cout << "The key[" << i << "] is: '" << keys[i] << "'." << std::endl;
// if the key is just a bunch of bytes, num_keys[i] in number:
for (int j = 0; j != num_keys[i]; ++j)
{
std::cout << "key[" << i << "][" << j << "] = " << (unsigned int)(keys[i][j]) << std::endl;
}
}
I put the printing in the same loop that does the reading; you could also do the printing in a separate loop if you preferred.
Assuming that array has type char **. You can do this with
printf("%c", array[i][j])
Here "%c" is acting as a format string telling it to expect a char from the next argument.