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=(cons t byte &w) { v = w.v; return *this; }
byte &operator=(cons t 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
3 20743 JosAH 11,448
Recognized Expert MVP
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
Banfa 9,065
Recognized Expert Moderator Expert
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.
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>(c onst T &w) : v(w.v) { }
byte_templ<T>(c onst byte_templ<T> &w) : v(w) { }
byte_templ<T> &operator=(cons t byte_templ<T> &w) { v = w.v; return *this; }
byte_templ<T> &operator=(cons t T &w) { v = w; return *this; }
operator T() const { return v; }
operator T &() { return v; }
};
std::ostream &operator<<(std ::ostream &os, const byte_templ<unsi gned char> &b) {
os << (unsigned short)b;
return os;
}
std::istream &operator>>(std ::istream &is, byte_templ<unsi gned char> &b) {
unsigned short i;
is >> i;
b = (unsigned char)i;
return is;
}
typedef byte_templ<unsi gned 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
Sign in to post your reply or Sign up for a free account.
Similar topics |
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 charcters are
implemented via integers.
Thanks,
Aditya
|
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 & 0xff)
one unsigned char is 1 byte, could anyone tell me the conversion
method?
|
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 use the native dll directly from c#
// CharSet = CharSet.Auto, CallingConvention
=CallingConvention.StdCall )]
public static extern short PAF_GetRecord(short listndx, short recno,
ref string pafrec, ref short pafreclen );
|
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?
|
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 c language such as
'byte'. Is it always okay to assume that the char data type is always
1 byte, or is there some other way to be sure you are getting 1 byte
that is not processor/OS dependent that is better, or is there no way
to be both...
| |
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. How can I
convert the sets of 4 bytes to floats?
Thanks,
Greg Book
|
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 encoding too, but with no success.
Can someone provide details on how to handle the 2-byte char URLs and download the files?
Appreciate your suggestions/help in resolving it.
Here is my code:
|
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 ( !file_.read( chunkType, 4 ) ) goto error;
if ( !file_.read( buffer, 4 ) ) goto error;
|
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 i got
unsigned char tmp;
f32 test;
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |