1

I'm a beginning user in C++ and I want to know how to do this: How can I 'create' a byte from a string/int. So for example I've:

string some_byte = "202";

When I would save that byte to a file, I want that the file is 1 byte instead of 3 bytes. How is that possible? Thanks in advance, Tim

3
  • show writer code, because in there is the bug Commented Jun 1, 2010 at 16:20
  • 1
    So you're new to C++, so here are a few pointers: 1) write C++ code, or C code. Don't mix and match. 2) parashift.com/c++-faq-lite is an awesome place to learn how to write C++ code. Commented Jun 1, 2010 at 16:35
  • By mix and match, I mean, don't mix and match C and C++ idioms. You can call C code from your C++ code, and likewise allow C code to call your C++ code. Commented Jun 1, 2010 at 16:49

4 Answers 4

4

I would use C++'s String Stream class <sstream> to convert the string to an unsigned char.

And write the unsigned char to a binary file.

so something like [not real code]

std::string some_byte = "202";
std::istringstream str(some_byte);
int val;
if( !(str >> val))
{
  // bad conversion
}

if(val > 255)
{
  // too big
}

unsigned char ch = static_cast<unsigned char>(val);

printByteToFile(ch); //print the byte to file.
Sign up to request clarification or add additional context in comments.

1 Comment

But reading an unsigned char from the stream will read only one byte, and store it directly. You have to read an int in order to make istream understand it as a number.
2

The simple answer is...

int value = atoi( some_byte ) ;

There are a few other questions though.

1) What size is an int and is it important? (for almost all systems it's going to be more than a byte)

int size = sizeof(int) ;

2) Is the Endianness important? (if it is look in to the htons() / ntohs() functions)

16 Comments

And what happens if I feed nonsense to atoi()? -1
Oh, and the result of sizeof is std::size_t, not int.
@sbi - what happens if you feed nonsense to your answer? Seriously man.
@sbi - re nonsense to atio() GIGO - en.wikipedia.org/wiki/Garbage_In,_Garbage_Out
@sbi- maybe the result of sizeof is a std::size_t- but let's be honest, what the hell kind of sized object do you have where it's size won't fit in an int?
|
2

In C++, casting to/from strings is best done using string streams:

#include <sstream>
// ...
std::istringstream iss(some_string);
unsigned int ui;
iss >> ui;
if(!iss) throw some_exception('"' + some_string + "\" isn't an integer!");
unsigned char byte = i;

To write to a file, you use file streams. However, streams usually write/read their data as strings. you will have to open the file in binary mode and write binary, too:

#include <fstream>
// ...
std::ofstream ofs("test.bin", std::ios::binary);
ofs.write( reinterpret_cast<const char*>(&byte), sizeof(byte)/sizeof(char) );

Comments

-1

Use boost::lexical_cast

#include "boost/lexical_cast.hpp"
#include <iostream>

int main(int, char**)
{
    int a = boost::lexical_cast<int>("42");
    if(a < 256 && a > 0)
        unsigned char c = static_cast<unsigned char>(a);

}

You'll find the documentation at http://www.boost.org/doc/libs/1_43_0/libs/conversion/lexical_cast.htm

However, if the goal is to save space in a file, I don't think it's the right way to go. How will your program behave if you want to convert "257" into a byte? Juste go for the simplest. You'll work out later any space use concern if it is relevant (thumb rule: always use "int" for integers and not other types unless there is a very specific reason other than early optimization)

EDIT As the comments say it, this only works for integers, and switching to bytes won't (it will throw an exception). So what will happen if you try to parse "267"? IMHO, it should go through an int, and then do some bounds tests, and then only cast into a char. Going through atoi for example will result extreamly bugs prone.

3 Comments

sizeof(int) is usually not 1.
Streaming an integer to cout will convert it back to a decimal string.
I'd change the type from int to a unsigned char, to prevent any values larger than 255.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.