How to implement binary128 in C? [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I started to try and implement new data types, specifically floating-point values, using C. I came up with this sort of way on implementing binary128 using longer_int which I haven't fully understood.
The way how I started was to implement it via copying the code and modifying it. However, the code is C++, and C doesn't support OOP, so what I have to do is to try and translate the code.
I can't find the C version for longer_int because this question I once owned (the same account but now deleted) is now deleted and I can't view the links.
With the help of these C++ files, how can I implement binary128 using C?
And just so this question won't get closed, I want to know how to translate the OOP format in longer_int.h.
class longer_int {
private:
char num_str[];
public:
longer_int();
longer_int(const int &num);
longer_int(const char &num[]);
longer_int(const longer_int &num);
// Sample code from it, now translated to C, but still OOP

You should begin with something like this: a struct instead of a class, ignore the public/private keywords, the constructors are methods that return the my_int128. There is no overloading in C, so each different constructor must have a different name. Another school of thought would say that you don't need specialized constructors, but simply special method setters that can copy data from an int, from a char[] and from a my_int128 (and I prefer this school of thought). I give an example setter at the end.
#include <stdio.h>
#include <string.h>
typedef struct
{
char num_str[16]; /* fixed to int128 */
} my_int128;
/* Don't need this: my_int128 li = { 0 }; is enough!
my_int128 create_int128()
{
my_int128 li = { 0 };
return li;
}
*/
my_int128 create_int128_from_num(int num)
{
my_int128 li = { 0 };
/* TODO: set li with num */
return li;
}
my_int128 create_int128_from_char_array(const char num[16])
{
my_int128 li = { 0 };
memcpy(li.num_str, num, 16);
return li;
}
my_int128 create_int128_from_int128_ptr(const my_int128 *num)
{
return create_int128_from_char_array(num->num_str);
}
The setter:
void set_from_int(my_int128 *li, int num)
{
/* TODO: set li with num */
}

Your best shot using C would be implementing binary128 as a structure type
struct binary128 {
unsigned char data[16];
};
Mind that there is no operator overloading in C, so you will need to implement all interaction with the type (like assignment from another type, arithmetic operations, so on) as functions.
Follow link in comments posted by Shawn to see more general case: implementation of integers of arbitrary width.

I assume that you have some C++ object code and you want to rewrite it in plain C. Once you think that first C++ compilers were just pre-processors that generate C code, it should not be too hard.
First the caveats:
C has no provision for encapsulation: functions can only have translation unit visibility or global visibility
C has no provision for function overwriting. One function can only have one set of parameters: use different names
That being said, to translate a C++ class, you build a C struct to hold the data members, and replace methods with plain functions. For that last part, you just replace the hidden this with an explicit pointer as an additional parameter.

Related

How to distinguish PODs and non PODs? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have an file handler, that reads and writes custom binary files. To save myself work I've inherited multiple data from one base struct (base_p):
struct base_p{
protected:
uint32_t v0= 0;
uint32_t v1= 0;
uint32_t v2= 0;
friend struct f_block;
// other friends
};
Now during building of my internal blocks of that file, I've inherited that struct into multiple non POD type:
struct f_block:public base_p{
f_block(){
this->v0 = 0x3f580058; // an magic number of the block
this->v1 = 0x1000004D; // version and use type
this->v2 = 0;
}
f_block(uint32_t data){
this->v0 = 0x3f580058; // an magic number of the block
this->v1 = 0x1000004D; // version and usage type
this->v2 = data;
}
operator uint8_t(){ return this->v1 & 0xff; }
operator bool(){return this->v2 != 0 ;}
friend std::ostream& operator<<( std::ostream& os, f_block& fb );
};
std::ostream& operator<<( std::ostream& os, f_block& fb ){
union {
uint32_t vrt;
unsigned char parts[4];
}temp;
temp. vrt = fb. v2;
return os << temp. parts[3] << temp. parts[2] << temp. parts[1] << temp. parts[0];
}
Inside my file handler, I have use for both structures. For example if I need to pass data somewhere, I need to extract data as base_p. But my block definition has an extra feature that usage serves and compression key and within data (v2) I have also stored some information such as bit offset from the end, length of featured blocks . . . and many others. So extracting function would look something along of lines:
struct file_handler{
std::vector<base_p> data;
file_handler():data(0){}
virtual bool read(const char *filename) = 0; // to be overridden
virtual bool write(const char *filename)= 0; // to be overridden
virtual bool set( base_p &data){
// if data is base_p , push_back data as normal POD
// if data is f_block, push_back data as deflated version
// don't store anything in vector if none
}
virtual bool get( base_p &data){
// if data is base_p, returns lasts 3 elements v2(data) fields
// if data is f_block, returns last element as f_block - inflated,
// set data as 0 if none
}
}
I've tried to catch an error of calling a function that doesn't exist in base_p, but it doesn't suit me since I am building multiple file handlers upon file_handler struct that should accept other data types. I am secure enough to start building other file types once I can successfully implement file_handler. What I need is something along of data type switch statement.
Since I come from python background, in it I could do something along of lines isinstance or something similar. But this is C++ so there isn't such implementation - that I am aware of.
I have searched and I've found some elements that seem to have potential to solve my problem, but most of them are for outdated versions or too abstract to wrap my head around to generate an logic solution.
SFINAE and void : mentions some sort of concept that SFINAEs follow, and compound concepts which is too abstract in question for me to successfully make valid implementation.
HasMember SFINAE : which seems feasible for constructor recognition, but best answer is written in c++03 with no mention if it translates to c++11 aka version I am currently using.
Is there a way to distinguish between PODs and non-PODs ?
I come from python background
C++ is not Python.
If all you have is a void* and no idea where it came from or what object it points to, then there is nothing you can do. C++ is a statically-typed language. This means that objects do not automatically store within themselves anything which identifies them as being of a particular type. All of that typing information is done at compile-time based on the types the compiler sees in the code.
The type present here is void, which is the "not a type" type. So any typing information has been lost. And it cannot be recovered by looking at some bytes behind a void*.
As far as the contents of the first byte behind that void* is concerned, there is no difference between a pointer to subs and a pointer to a my_data.
It sounds like you want to be able to take an arbitrary block of bytes, and determine whether those bytes constitute the underlying representation of an instance of the type my_data.
You can't. No such thing is meaningful. Those bytes do not have a type.
You will have to manually deserialise the bytes, using rules that you devise, picking out whether the values that lie therein (when so interpreted) match the preconditions for values in your my_data objects.
Usually we'd manage the data ourselves with some "header", indicating "this is an instance of a my_type" so that you at least know with some probability that it is so (don't forget this header may still be found in arbitrary data by pure chance). But you need to build that logic into the serialisation stage (on the way out) as well.

Is there anyway for the array at the end of class to work? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I got an array at the end of my class and i don't know how to use it.
the bus[10] is so hard to understand. I don't know why it can access driver and what does empty() function really do.
#include "conio.h"
#include "stdio.h"
#include "iostream.h"
#include "string.h"
#include "graphics.h"
#include "stdlib.h"
#include "dos.h"
static int p=0;
class a
{
char driver[10];// driver
public:
void install();// for installing
}bus[10];//here we declare the number of buses we can have.
void a::install()
{
cout<<"Enter bus no: ";//ques
cin >> bus[p].driver;// what does this mean
bus[p].empty();//what does this mean
p++;
}
This is syntax for defining a type, and an instance of that type, at the same time.
For example:
struct Foo {} foo;
is the same as:
struct Foo {};
Foo foo;
So your example defines the type a, and also creates an array of 10 as called bus.
It would be more clearly written thus:
class a
{
char driver[10];
public:
void install();
};
a bus[10];
In this manner we can now more easily see that you've created a global array called bus, which you can use like you'd use any other array.
Since p is zero (to begin with), bus[p] just gives you the "first" a object in the array (to begin with). As p is increased, subsequent buses are accessed.
So, this:
cin >> bus[p].driver;
reads into the driver member of the pth bus.*
And this:
bus[p].empty();
means nothing, because a does not have a member function called empty().
* Well, the p+1th bus, because array indices begin at zero but English doesn't!
P.S. You can do funny (read: stupid) things with this syntax!
This is a very strange looking code, probably from an old workbook.
I could help you with achieving the action that you want, but it's hard to understand anything from this snippet.
Wrong: As far as I remember adding a identifier at the end of an unnamed struct gave it a name just like the usual approach.
struct {
float x, y;
} Point;
//is equal to
struct Point {
float x, y;
}
However I'm not familiar with the array syntax you provided.
I suppose std::cin >> bus[p].driver is meant to read the "name" that the char[10] driver field is. But using a char array here is troublesome and it's much better to replace it with std::string and shortening it to 10 characters after input.
The empty() method is often used as a container function returning boolean and telling the programmer whether the container is empty or not. Here however this function is undeclared and the code won't compile either way.
Not to mention that non-const variables placed out of function scope, like the static int p = 0, are a grave mistake.
Not true: In conclusion this is a very messy code and without the knowledge of what you want to achieve nobody could help you here.
See the answer below for better explanation.

C++: Force separate instances of a class for code protection [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
This may sound strange, but for purposes of obfuscation, I'm wondering if there's a way to create multiple instances of a class throughout my app, but instead of them all reusing the same underlying code, the compiler would create completely separate chunks of code for that class. Sort of an inline for a class.
This would need to work in Xcode and Visual Studio.
The reason for this, and in all fairness, this is an idea that I'm just playing with...I'm looking for another level to slow down a hacker from patching my license code. Typically, no matter how hard you try to prevent code hacking, there ends up being one place where your code returns something like a true/false....Is this license valid? And if a hacker finds that one spot, it's a simple patch. My idea is to try putting the license code, specially the same license class, all throughout my app...many of them...and check any one of them at any time. And if it's done well, the hacker might have to find 10 of them...not knowing that there's really something like 20 of them throughout my app. And all this would depend on writing one class, but it can't be the same piece of reused class code...they'd need to be all separate.
Any ideas?
Here is an attempt/proof of concept. I've drafted a class which has:
some garbage data based on a template argument, so it's harder to reuse data layout.
a method with side effect based on on a template argument, so it's harder to reuse the code
One should be aware that this is all tricky, because compiler is allowed to do any transformation on the code which preserves observable behaviour. Thus, just using a template with a param, would produce two distinct type language wise, but the code generated could be reused for both.
I am not sure whether an experienced hacker would draw any conclusions about the code, or even whether the license check code itself would be duplicated. It's possible. Below code shows that method has two occurences in which one is a loop and the other got unwound, see on godbolt assembly lines 108-113 and 134-142.
That being said, often optimization is a nice obfuscator. Maybe on times even better than hand-mangling.
This a way to start. Generally constexpr and templates are our friends in such cases, because they are processed at compile time, we need to ensure the generate unique things. One could probably try some constexpr hashing, etc.
Code:
#include <string>
#include <iostream>
using std::string;
using std::cout;
template<int N>
struct B {
constexpr B() : arr() {
for (auto i = 0; i != N; ++i)
arr[i] = i;
}
int arr[N];
};
template<int Randomizer = 42>
struct A{
string a{"data_a"}; // probably all member should be templated by Randomizer
B<Randomizer> padding;
string b{"data_b"};
void method() {
cout << a << "\n";
for(int i = 0; i<Randomizer; i++) {
cout << padding.arr[i]; // harmless side effect
}
cout << "\n" << b << "\n";
}
};
int main () {
A<> i1;
A<3> i2;
i1.method();
i2.method();
return 0;
}

why not use static function-pointers in c++ [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I want a maintainable array/list of possible functions/behaviors, each representing another mode of operation, and I want to change the 'mode' simply by changing a variable storing the pointer to the right function. With researching I found the fact, that function-pointers are a bit smelly, but I wonder if
Ait is okay in my usecase to use them anyway
Bthere is a better/professional option.
Some pseudocode to show my prefered way of using it:
// store references to the modes and an information about the active mode
void * allModePointers[3];
int modeNumber = 2;
// call the active mode
(*allModePointers[modeNumber])();
void* is quite liberal with what type it accepts. By using it you give up compile time type checking. It is also hard to understand without typedef void* ModeFunctionPtr.
To get type checking and avoid pointer casting, you need a properly declared function pointer array like void(*allModePointers[3])() (verified by cdecl.org). This only works when the function signatures match, and if they don't, you are doing something wrong.
In the end, I would recommend std::function, which is a wrapper for callable objects. It has the advantage of being able to accept lambda expression, and works well with other std functions like std::bind if you one day find that static functions are not enough.
Short answer: When using C++ the most professional way to implement behaviors that do not readily exist in a library is to use a class.
Specific advice: if I understand your intent correctly, you want to model something like a terminal (i.e. performs a task based on a command). What I would do is make a class that only has functions (I have done this before to model a calculator) and maybe some static constants thrown in if you need them. One of the functions will be a control function that just takes in the command and calls one of the other functions based on that command, then returns the answer. Throw it in a .h, make it look neat with Doxygen and voila! You have your maintainable list of behaviors. I will demonstrate below using my calculator example. The one I made was to do vector calc, but I will make a simple one that only adds and squares.
/* doxygen comments */
/* include guards, includes, etc, etc */
class Calculator{
public:
/* static constants if needed (i.e. pi, e, ...) */
/* constructor, destructor, getters if you want to make the
constants private */
/* doxygen comments */
double run( int function_id, double x, double y ){
switch( function_id ){
case 0: return add( x, y );
case 1: return square( x );
default: return x; //why not?
}
}
private:
/* doxygen comments */
inline double square( double x ) { return x*x; }
/* doxygen comments */
inline double add( double x, double y ) { return x+y; }
};
Although this example is a little different than mine because I actually just made all the functions public and called them myself from main. Anyway, you get the gist, but there's probably less memory expensive ways of doing it as well.

Changing the value of an attribute dynamically in cpp [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a struct :
struct Person{
int scoreone;
int scoretwo;
int scoretotal;
}
main(){
Person a;
a.scoreone=3;
a.scoretwo=5;
//and later
a.scoreone=10;
}
I want the scoretotal to be updated when scoreone and scoretwo are chnaged without using any function.
Thanks
That can't be done in C++. The C++ way to handle this is to convert scoretotal to a method
struct Person{
int scoreone;
int scoretwo;
int scoretotal() { return scoreone + scoretwo; }
};
Now instead of saying person.scoretotal you say person.scoretotal() and the score total will be recalculated each time.
Can't be done--to change a value automatically, you need to run some code, and (in either C or C++) code is always in a function.
The rest of this answer assumes the use of C++, and won't work in C at all.
You can, however, keep the fact that it's a function from being externally visible, which (I'd guess) is what you care about:
struct Person {
int scoreone;
int scoretwo;
class total {
int *a, *b;
public:
total(int *a, int *b) : a(a), b(b) {}
operator int() { return *a + *b; }
} scoretotal;
Person() : scoretotal(&scoreone, &scoretwo) {}
};
This does have a (usually minor) side effect. It depends upon an implicit conversion from Person::total to int to do its job. That can lead to unexpected results in a couple of situations. One would be if you're trying to use some_person.scoretotal in a situation where you expect an implicit conversion from int to some other type. You're already using an implicit conversion from Person::total to int, and the compiler will only use one user-defined conversion implicitly, that would fail. In the other direction, if you were to use auto x = some_person.scoretotal;, x would be a Person::total rather than an int, because auto would deduce the actual type without the implicit conversion happening.
As long as you do relatively obvious things like:
Person some_person;
some_person.scoreone = 1;
some_person.scoretwo = 2;
int total = some_person.scoretotal;
std::cout << "Total score: " << some_person.scoretotal;
...you'll get scoretotal tracking the total of scoreone and scoretwo without making it obvious that a function has to be invoked to do that.
Irrespective of the language that you are using, the fundamental problem is in the design of your struct. There are only two independent data values in this structure. But you are storing three. That is the mistake.
What you need to to is store just the two primary values, scoreone and scoretwo. Those are the data. The other value is a derived value defined by the relationship that the total is equal to the sum scoreone + scoretwo.
So you should remove the data member scoretotal and replace it with a function if you are coding in C, or a member function if you are coding in C++. In C the code might look like this:
struct Person{
int scoreone;
int scoretwo;
};
int scoretotal(const struct Person person)
{
return person.scoreone + person.scoretwo;
}
If you declare struct Person the way john did in his answer you should not get an error when calling the scoretotal function. Remember to include the parentheses, saying "person.scoretotal" won't work, you have to write "person.scoretotal()" because you're calling a function in the Person-struct, not asking for a member.