Iterating through integer by byte in C++ - c++

I tried to iterate through an integer using a char pointer. My question is: Why is it stored in memory backwards? When I run the code:
#include <iostream>
using namespace std;
int main(int count, char** args)
{
unsigned int number = 0xabcdef12;
cout << "Number:\t\t" << hex << number << endl;
cout << "Iterated:\t";
unsigned char* pointer = (unsigned char*)&number;
for(int i=0; i<sizeof(number); i++)
cout << hex << (unsigned int)pointer[i];
cout << endl;
return 0;
}
The output is:
Number: abcdef12
Iterated: 12efcdab
I want to know if there is a way to force C++ to order the bytes, e.g.:
Number: abcdef12
Iterated: abcdef12
(Extra info: I want to do this because I want to iterate through a struct by byte and write the result to file.)

This is because you're on a "little-endian" system. Some computers, including the x86 ones most of us use, are this way. You can swap the byte order of an int with the standard function htonl(); the result will always be in "network byte order" which is the one you were expecting here.

Related

Converting an integer to Char Pointer using C

I am trying to convert an integer to a char pointer as shown below. The data results are different. I am not sure what is going wrong. Please help me in correcting the code.
int main(){
char *key1 = "/introduction";
std::ostringstream str1;
str1<< 10;
std::string data=str1.str();
std::cout <<"The data value="<<data<<std::endl; // The data value= 10
char *intro= new char[data.length()+1];
strcpy(intro, data.c_str());
std::cout <<"The data value="<<*intro <<std::endl; // The data value=1
return 0;
}
I am not sure why two data value are printed different i.e, 10 and 1.
In C++, when trying to print all the contents of a char * with cout, you should pass the pointer, i.e. cout << intro << endl.
What you've done here is dereferenced the char *, so cout << *intro << endl is equivalent to cout << intro[0] << endl, which is equivalent to printing the first character, 1.

How to convert char(or string, other type) -> bits?

In c++,
I don't understand about this experience. I need your help.
in this topic, answers saying use to_string.
but they say 'to_string' is converting bitset to string and cpp reference do too.
So, I wonder the way converting something data(char or string (maybe ASCII, can convert unicode?).
{It means the statement can be divided bit and can be processed it}
The question "How to convert char to bits?"
then answers say "use to_string in bitset"
and I want to get each bit of my input.
Can I cleave and analyze bits of many types and process them? If I can this, how to?
#include <iostream>
#include <bitset>
#include <string>
using namespace std;
int main() {
char letter;
cout << "letter: " << endl;
cin >> letter;
cout << bitset<8>(letter).to_string() << endl;
bitset<8> letterbit(letter);
int lettertest[8];
for (int i = 0; i < 8; ++i) {
lettertest[i] = letterbit.test(i);
}
cout << "letter bit: ";
for (int i = 0; i < 8; ++i) {
cout << lettertest[i];
}
cout << endl;
int test = letterbit.test(0);
}
When executing this code, I get result I want.
But I don't understand 'to_string'.
An important point is using of "to_string"
{to_string is function converting bitset to string(including in name),
then Is there function converting string to bitset???
Actually, in my code, use the function with a letter -> convert string to bitset(at fitst, it is result I want)}
help me understand this action.
Q: What is a bitset?
https://www.cplusplus.com/reference/bitset/bitset/
A bitset stores bits (elements with only two possible values: 0 or 1,
true or false, ...).
The class emulates an array of bool elements, but optimized for space
allocation: generally, each element occupies only one bit (which, on
most systems, is eight times less than the smallest elemental type:
char).
In other words, a "bitset" is a binary object (like an "int", a "char", a "double", etc.).
Q: What is bitset<>.to_string()?
Bitsets have the feature of being able to be constructed from and
converted to both integer values and binary strings (see its
constructor and members to_ulong and to_string). They can also be
directly inserted and extracted from streams in binary format (see
applicable operators).
In other words, to_string() allows you to convert the binary bitset to text.
Q: How to to I convert convert char(or string, other type) -> bits?
A: Per the above, simply use bitset<>.to_ulong()
Here is an example:
https://en.cppreference.com/w/cpp/utility/bitset/to_string
Code:
#include <iostream>
#include <bitset>
int main()
{
std::bitset<8> b(42);
std::cout << b.to_string() << '\n'
<< b.to_string('*') << '\n'
<< b.to_string('O', 'X') << '\n';
}
Output:
00101010
**1*1*1*
OOXOXOXO

C++ C4244 =': conversion from 'std::streamsize' to 'unsigned short', possible loss of data; any solution?

I'm fairly new to C++ and I just got done learning about Classes. I don't know why I keep getting this error C4244(check title).
I'm using Visual Studio 2017
Feedback would be appreciated.
//my program askes users to enter a sentence
`
#include <iostream>
using namespace std
Const short MAX = 132;
class information
{
char sentence[MAX];
short gcount;
public:
unsigned short CharCount;
void InputData();
void showresult();
};
Int main()
{
Information data;
data.InputData();
data.showresult();
return 0;
}
void information::InputData()//member function to enter info
{
cin.ignore(10, '\n');
cout << "Enter your sentence " << endl;
cout << endl;
cin.getline(sentence, sizeof(sentence));
CharCount = cin.gcount(); // this is the problem
}
void information::showresult() //show number of characters
{
cout << " Characters in the sentence:: " << CharCount << endl;
system(“Pause”);
}
`
The warning is telling you that you are trying to store a value that might be too large for the container you are trying to put it in. cin.gcount() returns a value of type std::streamsize. This is typically a signed 64-bit (or 32-bit) number. CharCount is an unsigned short, which is typically 16-bits.
Effectively, you are trying to store a signed 64-bit value into an unsigned 16-bit value, which the compiler is not happy with. You should change CharCount to be of type std::streamsize as well.
Or, as suggested by user253751, since you know it'll be a small size (132), you can just cast to an unsigned short.

OpenCV documentation says that "uchar" is "unsigned integer" datatype. How?

I got confused with the openCV documentation mentioned here.
As per the documentation, if i create an image with "uchar", the pixels of that image can store unsigned integer values but if i create an image using the following code:
Mat image;
image = imread("someImage.jpg" , 0); // Read an image in "UCHAR" form
or by doing
image.create(10, 10, CV_8UC1);
for(int i=0; i<image.rows; i++)
{
for(int j=o; j<image.cols; j++)
{
image.at<uchar>(i,j) = (uchar)255;
}
}
and then if i try to print the values using
cout<<" "<<image.at<uchar>(i,j);
then i get some wierd results at terminal but if i use the following statement then i can get the values inbetween 0-255.
cout<<" "<<(int)image.at<uchar>(i,j); // with TYPECAST
Question: Why do i need to do typecast to get print the values in range 0-255 if the image itself can store "unsigned integer" values.
If you try to find definition of uchar (which is pressing F12 if you are using Visual Studio), then you'll end up in OpenCV's core/types_c.h:
#ifndef HAVE_IPL
typedef unsigned char uchar;
typedef unsigned short ushort;
#endif
which standard and reasonable way of defining unsigned integral 8bit type (i.e. "8-bit unsigned integer") since standard ensures that char always requires exactly 1 byte of memory. This means that:
cout << " " << image.at<uchar>(i,j);
uses the overloaded operator<< that takes unsigned char (char), which prints passed value in form of character, not number.
Explicit cast, however, causes another version of << to be used:
cout << " " << (int) image.at<uchar>(i,j);
and therefore it prints numbers. This issue is not related to the fact that you are using OpenCV at all.
Simple example:
char c = 56; // equivalent to c = '8'
unsigned char uc = 56;
int i = 56;
std::cout << c << " " << uc << " " << i;
outputs: 8 8 56
And if the fact that it is a template confuses you, then this behavior is also equivalent to:
template<class T>
T getValueAs(int i) { return static_cast<T>(i); }
typedef unsigned char uchar;
int main() {
int i = 56;
std::cout << getValueAs<uchar>(i) << " " << (int)getValueAs<uchar>(i);
}
Simply, because although uchar is an integer type, the stream operation << prints the character it represents, not a sequence of digits. Passing the type int you get a different overload of that same stream operation, which does print a sequence of digits.

C++ Confusion. Reading Integer From Text File. Convert to ASCII

I am learning C++ for the first time. I have no previous programming background.
In the book I have I saw this example.
#include <iostream>
using::cout;
using::endl;
int main()
{
int x = 5;
char y = char(x);
cout << x << endl;
cout << y << endl;
return 0;
}
The example makes sense: print an integer and the ASCII representation of it.
Now, I created a text file with these values.
48
49
50
51
55
56
75
I am writing a program to read this text file -- "theFile.txt" -- and want to convert these numbers to the ASCII value.
Here is the code I wrote.
#include <iostream>
#include <fstream>
using std::cout;
using std::endl;
using std::ifstream;
int main()
{
ifstream thestream;
thestream.open("theFile.txt");
char thecharacter;
while (thestream.get(thecharacter))
{
int theinteger = int(thecharacter);
char thechar = char(theinteger);
cout << theinteger << "\t" << thechar << endl;
}
system ("PAUSE");
return 0;
}
This is my understanding about the second program shown.
The compiler does not know the exact data type that is contained in "theFile.txt". As a result, I need to specify it so I choose to read the data as a char.
I read the each digit in the file as a char and converted it to an integer value and stored it in "theinteger".
Since I have an integer in "theinteger" I want to print it out as a character but char thechar = char(theinteger); does not work as intended.
What am I doing incorrect?
You are reading char by char, but you really (I think) want to read each sequence of digits as an integer. Change your loop to:
int theinteger;
while (thestream >> theinteger )
{
char thechar = char(theinteger);
cout << thechar << endl;
}
+1 For a very nicely formatted & expressed first question, BTW!
You are reading one char at a time from the file. Hence, if your file contains:
2424
You will first read the char "2" from the file, convert it to an int, and then back to a char, which will print "2" on cout. Next round will print "4", and so on.
If you want to read the numbers as full numbers, you need to do something like:
int theinteger;
thestream >> theinteger;
cout << char(theinteger) << endl;