473,320 Members | 1,936 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

byte vs char

Hi,

This is a question about declaring a signed 8bit numeric type in C++ that prints like a numeric variable and not like a char variable. I would like to declare a type with name 'byte' which represents 8bit numeric values. Of course C++ has char with the right size. So I tried
------
typedef char byte;
------
This is fine, until I tried
---------
byte b = 1;
cout << b;
---------
This (as expected) does not output '1' (as I would like), but rather the char with ascii code 1. Since I would prefer my numeric types to print as their decimal value (like int, doulbe, etc.), I tried
--------
typedef char byte;
std::ostream &operator<<(std::ostream &os, const byte &b) {
os << (int)b;
return os;
}
-------
Now
--------
char b=62;
cout << b;
-------
prints '62' and not 'A'. It seems that typedef is simply aliasing and not actually creating a new type. My next attempt is to create a new type which just wraps char
---------
class byte {
char v;
public:
byte() : v() { }
byte(const byte &w) : v(w.v) { }
byte(const char &w) : v(w) { }

byte &operator=(const byte &w) { v = w.v; return *this; }
byte &operator=(const char &w) { v = w; return *this; }

operator char() { return v; }

friend std::ostream &operator<<(std::ostream &, const byte &);
friend std::istream &operator>>(std::istream &, byte &);
};

std::ostream &operator<<(std::ostream &os, const byte &b) {
os << (int)b.v;
return os;
}
------------
This works fine, except when compiling with g++ (GCC) 4.1.2 20071124 (Red Hat 4.1.2-42)
------
byte b = 0;
b++;
-----
produces:
error: no 'operator++(int)' declared for postfix '++', trying prefix operator instead
error: no match for 'operator++' in '++b'

This is rather odd because
------
byte b = 0;
b = b + 1;
-----
compiles fine (the conversion to unsigned char is called as intended).

So it seems like I have to declare ++, --, +=, .... At this point I gave up on this attempt because it seemed to me that the solution is already going out of hand for what I wanted originally.

Is there an elegant solution to this?

Thanks,
Vladimir
Nov 16 '08 #1
3 20557
JosAH
11,448 Expert 8TB
You're on the right track: indeed the old C typedef just creates a new name for
an already existing type and the pre- or postfix ++ isn't mapped to a x+1 binary
operator. If takes a bit of work to create an entirely new type that accepts the
same operators as the built-in primitives.

You can define the operators 'op' in terms of the 'op=' operators. The first one just
calls the second one on a copy of the the left hand operand. So you have to
create a copy constructor (which is trivial in your case).

Compare your 'byte' class with Bjarne Stroustrup's 'complex' class; they're similar.

kind regards,

Jos
Nov 16 '08 #2
Banfa
9,065 Expert Mod 8TB
Depending on how often you output bytes using cout you may find it easier just to static_cast your byte type'd variables to int in your cout statements.

This is one area where I have always felt that C++s attempt to guess how you want your variable output was rather less useful than C's basic insistence that you tell it how to do it.

Also if you want byte as an unsigned 8 bit variable then you need to define it as
typedef unsigned char byte
because the signedness of char is platform dependent.
Nov 16 '08 #3
Thanks, guys!

I fiddled with this some more over the weekend and found out that the following code works for me. Thought I would post this in case somebody is fighting with the same...
---------------------
template <class T>
class byte_templ {
T v;

public:
byte_templ<T>() : v() { }
byte_templ<T>(const T &w) : v(w.v) { }
byte_templ<T>(const byte_templ<T> &w) : v(w) { }

byte_templ<T> &operator=(const byte_templ<T> &w) { v = w.v; return *this; }
byte_templ<T> &operator=(const T &w) { v = w; return *this; }

operator T() const { return v; }
operator T &() { return v; }
};

std::ostream &operator<<(std::ostream &os, const byte_templ<unsigned char> &b) {
os << (unsigned short)b;
return os;
}

std::istream &operator>>(std::istream &is, byte_templ<unsigned char> &b) {
unsigned short i;

is >> i;
b = (unsigned char)i;
return is;
}

typedef byte_templ<unsigned char> byte;
---------------------
Now
---------------------
cin >> b;
b++;
cout << b;
---------------------
works as intended. Basically, I needed to add the cast to (unsigned char &), because 'b++' implicitly contains an assignment...

Best, Vladimir
Nov 17 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

20
by: adityavasishth | last post by:
hi all, Characters are basically implemented via integers,ex : '\0' is 0.But integers requires 2 bytes and the characters require only 1 byte.So,can anybody please tell me that how the...
11
by: QQ | last post by:
I know a char is 2 bytes, the conversion is like byte byte_array = new byte; //Allocate double mem as that of char then for each char do byte = (byte) char & 0xff byte = (byte)( char >> 8 &...
2
by: caviar | last post by:
I'm trying to read in a ref parameter from a native dll, its working in vb if i use the kernel32 functions below transforming the ref param to a vb string: Now, i want to skip this vb dll and...
15
by: Kueishiong Tu | last post by:
How do I convert a Byte array (unsigned char managed) to a char array(unmanaged) with wide character taken into account?
14
by: rsood | last post by:
Hi I'm developing a program, and naturally I want it to be as portable as possible. I need to be able to access specific numbers of bytes in it, but as far as I know, there is no keyword in the...
9
by: Gregory.A.Book | last post by:
I am interested in converting sets of 4 bytes to floats in C++. I have a library that reads image data and returns the data as an array of unsigned chars. The image data is stored as 4-byte floats....
0
by: jinnareddy | last post by:
Hi, I'm unable to download a file that is having a 2-byte char in its name (e.g.テ) using force download option. Though, am able to download file names involving ASCII chars. I have tried URL...
5
by: Chlikaflok | last post by:
See, I have this code, I'm trying to open and run a MIDI file, and I'm parsing the header to check it's integrity : // Parse header info. char chunkType; char buffer; SINT32 *length; if (...
4
by: MrL0co | last post by:
he there, I am trying to read out a .md3 file. i am stuck on a point where i have to convert a 8-bit hexedecimal char to a float. and change it from little endian to big endian this is how far...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.