c++,sockets,encryption,endianness,blowfish , Blowfish encryption and decryption across c sockets


Blowfish encryption and decryption across c sockets

Question:

Tag: c++,sockets,encryption,endianness,blowfish

I'm using the following implementation of blowfish (with some stuff cut out of the middle) to encrypt and decrypt messages. I am attempting to encrypt a message on a big endian machine (SunOS 5.10), and then send it over a socket to a little endian machine (linux). I can encrypt and decrypt on the same machine, and on different linux machines, but I can't get it to work between these two machines.

Because the blowfish implementation seems to break the message up into DWords, each of which contains two 32 bit integers, I have been breaking my encrypted message into 32 bit integers, applying htonl() to each, sending them over the network, applying ntohl() to each, and then attempting to decrypt. The result is not pretty, but interestingly enough, most of the correct characters are present after decryption, but they are garbled and some extra garbage characters appear in some places. I really can't imagine what I might be missing.

/********** blowfish.h **********/

#ifndef ___BLOWFISH_H___
#define ___BLOWFISH_H___


#define NUM_SUBKEYS  18
#define NUM_S_BOXES  4
#define NUM_ENTRIES  256

#define MAX_STRING   256
#define MAX_PASSWD   56  // 448bits

#ifdef BIG_ENDIAN
struct WordByte
{
    unsigned int zero:8;
    unsigned int one:8;
    unsigned int two:8;
    unsigned int three:8;
};
#endif

#ifdef LITTLE_ENDIAN
struct WordByte
{
    unsigned int three:8;
    unsigned int two:8;
    unsigned int one:8;
    unsigned int zero:8;
};
#endif

union Word
{
    unsigned int word;
    WordByte byte;
};

struct DWord
{
    Word word0;
    Word word1;
};


class Blowfish
{
private:
  unsigned int PA[NUM_SUBKEYS];
  unsigned int SB[NUM_S_BOXES][NUM_ENTRIES];

  void Gen_Subkeys(char *);
  inline void BF_En(Word *,Word *);
  inline void BF_De(Word *,Word *);

public:
  Blowfish();
  ~Blowfish();

  void Reset();
  void Set_Passwd(char * = NULL);
  void Encrypt(void *,unsigned int);
  void Decrypt(void *,unsigned int);
};


#endif



/********** blowfish.cc **********/

#include <iostream.h>
#include <string.h>
#include "blowfish.h"


#define F(x)    (((SB[0][x.byte.zero] + SB[1][x.byte.one]) ^ SB[2][x.byte.two]) + SB[3][x.byte.three])


void Blowfish::Gen_Subkeys(char *Passwd)
{
  unsigned int i,j,len=strlen(Passwd);
  Word Work,null0,null1;

  if (len > 0)
  {
    j = 0;
    for (i=0;i<NUM_SUBKEYS;i++)
    {
    Work.byte.zero = Passwd[(j++)%len];
    Work.byte.one = Passwd[(j++)%len];
    Work.byte.two = Passwd[(j++)%len];
            Work.byte.three = Passwd[(j++)%len];
            PA[i] ^= Work.word;
        }

    null0.word = null1.word = 0;

    for (i=0;i<NUM_SUBKEYS;i+=2)
      {
            BF_En(&null0,&null1);
        PA[i] = null0.word;
            PA[i+1] = null1.word;
        }

    for (j=0;j<NUM_S_BOXES;j++)
            for (i=0;i<NUM_ENTRIES;i+=2)
        {
        BF_En(&null0,&null1);
        SB[j][i] = null0.word;
        SB[j][i+1] = null1.word;
        }
   }

   Work.word = null0.word = null1.word = 0;
   Passwd = NULL;
   len = 0;
}

void Blowfish::BF_En(Word *x1,Word *x2)
{
  Word w1=*x1,w2=*x2;

  w1.word ^= PA[0];
  w2.word ^= F(w1)^PA[1];       w1.word ^= F(w2)^PA[2];
  w2.word ^= F(w1)^PA[3];       w1.word ^= F(w2)^PA[4];
  w2.word ^= F(w1)^PA[5];       w1.word ^= F(w2)^PA[6];
  w2.word ^= F(w1)^PA[7];       w1.word ^= F(w2)^PA[8];
  w2.word ^= F(w1)^PA[9];       w1.word ^= F(w2)^PA[10];
  w2.word ^= F(w1)^PA[11];      w1.word ^= F(w2)^PA[12];
  w2.word ^= F(w1)^PA[13];      w1.word ^= F(w2)^PA[14];
  w2.word ^= F(w1)^PA[15];      w1.word ^= F(w2)^PA[16];
  w2.word ^= PA[17];

  *x1 = w2;
  *x2 = w1;
}

void Blowfish::BF_De(Word *x1,Word *x2)
{
  Word w1=*x1,w2=*x2;

  w1.word ^= PA[17];
  w2.word ^= F(w1)^PA[16];      w1.word ^= F(w2)^PA[15];
  w2.word ^= F(w1)^PA[14];      w1.word ^= F(w2)^PA[13];
  w2.word ^= F(w1)^PA[12];      w1.word ^= F(w2)^PA[11];
  w2.word ^= F(w1)^PA[10];      w1.word ^= F(w2)^PA[9];
  w2.word ^= F(w1)^PA[8];       w1.word ^= F(w2)^PA[7];
  w2.word ^= F(w1)^PA[6];       w1.word ^= F(w2)^PA[5];
  w2.word ^= F(w1)^PA[4];       w1.word ^= F(w2)^PA[3];
  w2.word ^= F(w1)^PA[2];       w1.word ^= F(w2)^PA[1];
  w2.word ^= PA[0];

  *x1 = w2;
  *x2 = w1;
}


Blowfish::Blowfish()
{
  Reset();
}

Blowfish::~Blowfish()
{
  Reset();
}


void Blowfish::Reset()
{
  unsigned int i,j;

  unsigned int PA_Init[NUM_SUBKEYS] =
  {
    0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
    0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
    0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
    0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
    0x9216d5d9, 0x8979fb1b
  };

  unsigned int SB_Init[NUM_S_BOXES][NUM_ENTRIES] =
  {
    0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
    0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
    0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
    0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
    ...
    ...
    ...
  };

  for (i=0;i<NUM_SUBKEYS;i++)
    PA[i] = PA_Init[i];

  for (j=0;j<NUM_S_BOXES;j++)
    for (i=0;i<NUM_ENTRIES;i++)
      SB[j][i] = SB_Init[j][i];
}

void Blowfish::Set_Passwd(char *Passwd)
{
  char New_Passwd[MAX_STRING];
  unsigned int i,len;

    if (Passwd == NULL)
    {
    do
    {
    cout << "\aEnter your password: ";
    cin.get(New_Passwd,MAX_STRING,'\n');
    len = strlen(New_Passwd);
    }
    while (len > MAX_PASSWD);
    Passwd = New_Passwd;
  }
  else
    len = strlen(Passwd);

  Reset();
  if (len > 0)
    Gen_Subkeys(Passwd);

  for (i=0;i<MAX_STRING;i++)
    New_Passwd[i] = '\0';
   Passwd = NULL;
   len = 0;
}

void Blowfish::Encrypt(void *Ptr,unsigned int N_Bytes)
{
  unsigned int i;
  DWord *Work;

  if (N_Bytes%8)
  {
    cerr << "\aBlowfish requires the input to be a multiple of 8 bytes (64 bits) to work.\n";
    return;
  }

    N_Bytes /= 8;
  Work = (DWord *)Ptr;

  for (i=0;i<N_Bytes;i++)
  {
    BF_En(&Work->word0,&Work->word1);
    Work++;
  }

  Work = NULL;
}

void Blowfish::Decrypt(void *Ptr,unsigned int N_Bytes)
{
  unsigned int i;
  DWord *Work;

  if (N_Bytes%8)
  {
    cerr << "\aBlowfish requires the input to be a multiple of 8 bytes (64 bits) to work.\n";
    return;
  }

    N_Bytes /= 8;
  Work = (DWord *)Ptr;
  for (i=0;i<N_Bytes;i++)
  {
    BF_De(&Work->word0,&Work->word1);
    Work++;
  }

  Work = NULL;
}

The following is the encrypted string on the big-endian machine:

11010011 11110110 01100110 10001101 01010011 11000110 00010001 11110110 00011010 11001010 00011111 00100001 10110000 10110100 10110000 11110000 11111100 11000010 00110011 00001111 10011110 01100111 00010101 10000101 00001010 01111110 10000101 00011100 10010010 10111010 10010111 11111001 00111101 01011100 00000010 01010011 11100000 11001101 11111010 00111100 00011101 10001001 01010111 01011010 11100001 10101111 10001100 10111001 00011111 10111100 10010101 01101110 10001101 11010100 11101110 11010001 10111011 11111110 10100111 01111000 11010001 01011101 00110100 01000001 01011011 01111100 10010011 00010001 10100011 10011011 10111100 01100000

This is the encrypted string after I have sent it over the network to the little-endian machine:

10001101 01100110 11110110 11010011 11110110 00010001 11000110 01010011 00100001 00011111 11001010 00011010 11110000 10110000 10110100 10110000 00001111 00110011 11000010 11111100 10000101 00010101 01100111 10011110 00011100 10000101 01111110 00001010 11111001 10010111 10111010 10010010 01010011 00000010 01011100 00111101 00111100 11111010 11001101 11100000 01011010 01010111 10001001 00011101 10111001 10001100 10101111 11100001 01101110 10010101 10111100 00011111 11010001 11101110 11010100 10001101 01111000 10100111 11111110 10111011 01000001 00110100 01011101 11010001 00010001 10010011 01111100 01011011 01100000 10111100 10011011 10100011

Finally, this is what the string needs to be, in order for it to be successfully decrypted on the little-endian machine (i.e. this is what I get when I encrypt the original string on the little-endian machine, instead of the big endian machine):

10001101 10111011 10110010 10111000 01110001 11000110 00110110 10101110 11000011 11000100 00001010 10011110 11111101 10101000 01110011 10110110 00011001 10000011 11111000 11010001 01101001 00101100 10110001 00010001 11101101 10001011 01101110 01101011 11110001 01101010 00111010 00010110 11101111 01001111 11001100 00011101 01101010 11110000 00110000 01110100 10111010 01000101 01011001 11111001 11011101 01000011 10000110 01000001 11101110 00100001 00111000 00101001 11110011 00001111 01000011 11000000 10110010 10011101 11110000 00000001 10001011 10110101 10010011 01010010 01110100 11100000 10010011 10111101 00111110 00100001 10101111 11010000

I'm currently trying to compare the strings, but I can't find a pattern.


Answer:

I think your problem is that you try to use a byte string input without somehow endian correcting it so that the same mathematical calculations are being done on different endian platforms:

void Blowfish::Encrypt(void *Ptr,unsigned int N_Bytes)
{
  unsigned int i;
  DWord *Work;

  if (N_Bytes%8)
  {
    cerr << "\aBlowfish requires the input to be a multiple of 8 bytes (64 bits) to work.\n";
    return;
  }

  N_Bytes /= 8;
  Work = (DWord *)Ptr;  // NOTE: this won't work on some archs if Ptr isn't properly aligned on a 32b boundary

  for (i=0;i<N_Bytes;i++)
  {
    Work->word0 = ntohl(Work->word0);  // necessary to convert byte string to same number on different archs
    Work->word1 = ntohl(Work->word1);
    BF_En(&Work->word0, &Work->word1);
    Work->word0 = htonl(Work->word0);  // leave all encryptions in network byte order
    Work->word1 = htonl(Work->word1);
    Work++;
  }

  Work = NULL;
}

void Blowfish::Decrypt(void *Ptr,unsigned int N_Bytes)
{
  unsigned int i;
  DWord *Work;

  if (N_Bytes%8)
  {
    cerr << "\aBlowfish requires the input to be a multiple of 8 bytes (64 bits) to work.\n";
    return;
  }

  N_Bytes /= 8;
  Work = (DWord *)Ptr;  // NOTE: this won't work on some archs if Ptr isn't properly aligned on a 32b boundary

  for (i=0;i<N_Bytes;i++)
  {
    Work->word0 = ntohl(Work->word0);  // necessary to convert byte string to same number on different archs
    Work->word1 = ntohl(Work->word1);
    BF_De(&Work->word0, &Work->word1);
    Work->word0 = htonl(Work->word0);  // leave all decryptions in network byte order
    Work->word1 = htonl(Work->word0);
    Work++;
  }

  Work = NULL;
}

Note that with the above code, you wouldn't need to worry about the endianness of your data at the application level anymore. The same input byte string should encrypt/decrypt to the same output byte string on both platforms.


Related:


What type of database is the best for storing array or object like data [on hold]


database,node.js,sockets
I'm just curious what the best method would be if I'm trying to have a bot running on my Node server that I could play Blackjack against. But for multiple connected clients via sockets, each connected socket will have their own bot to play against but I need some way...

how to sort this vector including pairs


c++,vector
I want to sort in ascending order according to the first element of the inner pair, i.e. a in this case. But its not at all sorting. I am not sure if my function func logic is correct. #include<iostream> #include<algorithm> #include<vector> using namespace std; bool func(const pair<int,pair<int,int> >&i , const...

Specified argument was out of the range of valid value to get data from network in c#


c#,sockets,buffer,streamwriter
I am trying to send a command to a sensor and get the data from it using this code : const int PORT_NO = 3000; const string SERVER_IP = "192.168.2.44"; //---listen at the specified IP and port no.--- IPAddress localAdd = IPAddress.Any; TcpListener listener = new TcpListener(localAdd, PORT_NO); Console.WriteLine("Listening..."); listener.Start();...

Strings vs binary for storing variables inside the file format


c++,file,hdf5,dataformat
We aim at using HDF5 for our data format. HDF5 has been selected because it is a hierarchical filesystem-like cross-platform data format and it supports large amounts of data. The file will contain arrays and some parameters. The question is about how to store the parameters (which are not made...

Test if string represents “yyyy-mm-dd”


c++,command-line-arguments
I am working on a program that takes two command line arguments. Both arguments should be dates of the form yyyy-mm-dd. Since other folks will be using this program and it will be requesting from mysql, I want to make sure that the command line arguments are valid. My original...

C++11 Allocation Requirement on Strings


c++,string,c++11,memory,standards
I had heard that C++11 was going to require strings to be allocated in contiguous memory. I even thought I saw a stack overflow question on it, but I can't seem to find it. I know that in practice both gcc and Visual Studio do allocate strings contiguously, I'm just...

template template class specialization


c++,templates,template-specialization
I am just learning about Template Template class specialisation. Not a big problem to explain in detail. From my understanding std::uniform_int_distribution is a template whereas std::uniform_int_distribution<Type> is the full specialisation of uniform_int_distribution giving a type. I pass this in the specialisation class template as follows below Main class template <template...

Explicit instantiation of class template not instantiating constructor


c++,templates,constructor,explicit-instantiation
I'm working on a project in C++ and am having trouble understanding what members of a template class get explicitly instantiated when I explicitly instantiate the template class. I've written the following file, which I then compile using Visual C++ 2008 Express Edition's Release configuration and then pop into a...

Type function that returns a tuple of chosen types


c++,templates,c++11,metaprogramming
I've implemented a type function Tuple that turn a list of My_enum values into an std::tuple of corresponding types: #include <tuple> enum My_enum{ t_int, t_double }; // Bind_type is a type function that given a My_enum returns the corresponding type template<My_enum E> struct Bind_type; template<> struct Bind_type<t_int>{ using type =...

dispatch response packet according to packet sequence id


c++,boost,boost-asio
I have a third-part server, and I'm writing a dll interface for it, my clients use my dll to communicate with the server. The protocol uses a long tcp connection, all traffic goes from this tcp connection. There could be sending/receiving multiple packets at the same time, like a send_msg...

opencv window not refreshing at mouse callback


c++,opencv
I am trying to draw with mouse move in an opencv window. But when I draw, nothing draws on the window. When I try to close the window from the cross in the topleft(ubuntu), it opens a new window which it should be as I haven't pressed escape, and in...

C++ template template


c++,templates
I'm trying to understand C++ template templates by implementing a generic container class. Here is the code: using namespace std; template <typename T, template <typename STORETYPE> class Container> class Store { public: ~Store() {}; Store() {}; void someFunc( const T & ) {}; //... private: Container<T> storage; }; int main(int...

.cpp:23: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int atoi(const char*)’


c++,string
Here a basic code I'm trying to run But I'm having trouble with stoi (it's c++) I keep getting error: ‘stoi’ was not declared in this scope I tried atoi and strtol with this error .cpp:23: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int atoi(const char*)’...

How can I access the members of a subclass from a superclass with a different constructor?


c++,inheritance,constructor,subclass,superclass
I have the following class and typedef: class Object { protected: long int id; public: Object(void); ~Object(void) {}; long int get_id(void); }; typedef map<string, Object> obj_map; And then I have its child: class Image: public Object { private: path full_path; int x; int y; img image; public: Image(path p, int...

Add more features to stack container


c++,visual-c++,stl
I am using default features(push, pop, top, empty, size) of stack container of STL. If I want to add more features like access an element from middle of stack. How could I do this? Thanks...

Marshal struct in struct from c# to c++


c#,c++,marshalling
I have the following structures in C# and C++. C++: struct TestA { char* iu; }; struct TestB { int cycle1; int cycle2; }; struct MainStruct { TestA test; TestB test2; }; C#: [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 1)] internal struct TestA { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)] private string iu; public...

Checking value of deleted object


c++
I asked a question: Detecting if an object is still active or it has been destroyed Considering that I cannot use libraries, there are no good out of the box solutions in C++. So, is it a bad practice to check if the object has been destroyed by analyzing memory...

Method returning std::vector>


c++
As a continuation of a: Thread, I came across a problem with writing a method of a class which returns: std::vector<std::unique_ptr<Object>> I get compiler errors when such a return type is written. There is some problem with delete operand or something ... Generally, I've wanted to write a method which...

MFC visual c++ LNK2019 link error


c++,mfc
I just don't understand why i can use the public variables on the class but are getting a link error when trying to use the getLicenceRefused method. I wasn't sure if the problem was because of the CString copy constructor problem I have had before so took the parameter out,...

Incorrect Polar - Cartesian Coordinate Conversions. What does -0 Mean?


c++,polar-coordinates,cartesian-coordinates
I am getting incorrect conversions from polar to cartesian coordinates and vice versa. My code produces weird points like (1,-0). Im using this calculator to check my conversions. Also one of the conversions is completely wrong when I convert back to cartesian coordinates. Point b: (0,1) => (1,1.5708) => (0,0)...

Implicit use of initializer_list


c++,c++11,initializer-list
§[dcl.init.list] 8.5.4/2: The template std::initializer_list is not predefined; if the header <initializer_list> is not included prior to a use of std::initializer_list — even an implicit use in which the type is not named (7.1.6.4) — the program is ill-formed. Does that mean this program is ill-formed? #include <vector> int main()...

Undefined behaviour or may be something with memset


c++,undefined-behavior
I was trying to save the binary equivalent of a 32 bit number in an array A. For testing my showbits() function , I choosed 8,9 when I came across this thing: I am facing an unreasonable thing in my code when I am placing memset in the function showbits(),I...

How to get the socket's specific error reason when POLLERR happens?


sockets,epoll
When POLLERR comes up after polling, how can I determine the specific error reason?

Same function with and without template


c++,c++11
I am trying to understand a piece of code of C++11. A class contains 2 functions as shown below: class abc { public: void integerA(int x); template<typename typ> void integerA(typ x); }; I am unable to understand benefit of declaring 2 same functions. Why not declare only one template function?...

Should I use different WSAOVERLAPPED struct for WSASend and WSARecv?


windows,sockets,winsock,winsock2
I'm developing a server-client application using WinSock. Does using the same WSAOVERLAPPED with both WSASend and WSARecv works well? Should I use different WSAOVERLAPPED struct for WSASend and WSARecv?...

Passing something as this argument discards qualifiers


c++,c++11
Using the below code, i get the following compile error: In static member function ‘static std::string ctedata::Record::getDispatcher<std::basic_string<char> >::impl(const ctedata::Record&, const string&)’: /home/jason/CrownTheEmpire/lib/ctedata/data.h:111:38: error: passing ‘const std::map<std::basic_string<char>, std::basic_string<char> >’ as ‘this’ argument discards qualifiers [-fpermissive] return rec.fieldValues_[field]; ^ In file included from /usr/include/c++/5.1.0/map:61:0, from...

Make a triangle shape in C++


c++
I am trying to print out the shape of a triangle but I am kinda lost... this is what I have so far: #include <iostream> using namespace std; int main() { int i, k, n; cout << "Please enter number of rows you want to see: \n"; cin >> n;...

C++ Isn't this a useless inline declaration?


c++,inline,private,member,protected
This is another question about inlining a function. But I will take possible comments and answers right away: Defining a function inside a class makes it inline automatically. The same behaviour can be achieved by marking a function with inline outside of the class. An inline function doesn't have to...

How can I convert an int to a string in C++11 without using to_string or stoi?


c++,string,c++11,gcc
I know it sounds stupid, but I'm using MinGW32 on Windows7, and "to_string was not declared in this scope." It's an actual GCC Bug, and I've followed these instructions and they did not work. So, how can I convert an int to a string in C++11 without using to_string or...

C++ & Qt: Random string from an array area


c++,arrays,string,qt,random
In my small Qt application, I want to pick a random string out of an array after I clicked on a button. I've read many threads but nothing works for me. So in my slot there's an array with several strings in it. I also implemented <string>, <time.h> and srand....

Socket.IO message doesn't update Angular variable


javascript,angularjs,node.js,sockets
I have a socket.io client-server setup with AngularJS running on the client. // Server.js var io = require('socket.io')(server); io.on('connection', function (socket) { socket.on('message', function (msg) { //console.log(msg); console.log(msg); io.emit('message', msg); }); }); As observed, it essentially emits a message events with the data stored in the variable msg. And then...

OpenCV - Detection of moving object C++


c++,opencv
I am working on Traffic Surveillance System an OpenCv project, I need to detect moving cars and people. I am using background subtraction method to detect moving objects and thus drawing counters. I have a problem : When two car are moving on road closely them my system detects it...

segfault accessing qlist element through an iterator


c++,iterator,qlist
I get a segfault while iterating over a QList. I don't understand what I am doing wrong. I have a QList of Conversation. Inside a Conversation I have a QList of Msg. Below are the class description : Msg class : class Msg { public: Msg(); Msg(const Msg& other); Msg&...

Sockets make no sense?


javascript,node.js,sockets
I'm using the 'ws' library for Node.js. I can write code that sends data from my server to my client, posting a date and time update, and closes the socket when I click a button; var wss = new WebSocketServer({server: server}); console.log("WebSocket server created"); wss.on('connection', function(socket) { // SEND DATE...

Can python script know the return value of C++ main function in the Android enviroment


python,c++
There are several ways of calling C++ executable programs. For example, we can use def run_exe_return_code(run_cmd): process=subprocess.Popen(run_cmd,stdout=subprocess.PIPE,shell=True) (output,err)=process.communicate() exit_code = process.wait() print output print err print exit_code return exit_code to process a C++ executable program: run_exe_return_code('abc') while abc is created by the following C++ codes: int main() { return 1;...

Get an ordered list of files in a folder


c++,boost,boost-filesystem
I have used boost::filesystem::directory_iterator in order to get a list of all the available files into a given folder. The problem is that I supposed this method would give me the files in alphabetical order, while the results seem pretty random. Is there any fancy way of alphabetically sorting them?...

ctypes error AttributeError symbol not found, OS X 10.7.5


python,c++,ctypes
I have a simple test function on C++: #include <stdio.h> #include <string.h> #include <stdlib.h> #include <locale.h> #include <wchar.h> char fun() { printf( "%i", 12 ); return 'y'; } compiling: gcc -o test.so -shared -fPIC test.cpp and using it in python with ctypes: from ctypes import cdll from ctypes import c_char_p...

Why are shaders and programs stored as integers in OpenGL?


c++,opengl,opengl-es,integer,shader
I'm following the "OpenGL Superbible" book and I can't help but notice that when we create a shader and create the program that we attach the shaders to, we store them as GLuint which are unsigned integers. Why are they stored as numbers? What does the value of the number...

Issue when use two type-cast operators in template class


c++
I define a template class in which, I define two type-cast operator template <class base_t> struct subclass { base_t base; //any function which defined for 'base_t' can be used with 'subclass<base_t>' operator base_t&() { return base; } //I want 'subclass<base_t>' can be converted to any class which 'base_t' can //I...

undefined reference to `vtable for implementation' error


c++,build,makefile
I wrote some c++ files and after compiling with out make file it works fine . But when using make file it pop out some errors . My codes are : include directory files : application.h #ifndef APPLICATION_H #define APPLICATION_H #include "employee.h" #include "employee_data.h" #include "employee.h" ...some defintions here... #endif...

Validate case pattern (isupper/islower) on user input string


c++,user-input
I need to write a program that checks if the user-provided first and last names are correctly typed. The program needs to validate that only the first letter of each name part is uppercase. I managed to write code that checks the first character of the input. So I have...

3 X 3 magic square recursively


c++,algorithm,math,recursion
I'm trying to find all possible solutions to the 3X3 magic square. There should be exactly 8 solutions. My code gets them all but there are a lot of repeats. I'm having a hard time tracking the recursive steps to see why I'm getting all the repeats. // This program...

How can I tell clang-format to follow this convention?


c++,clang-format
I would like to have this: if (!enabled) { return; } turned to this: if (!enabled) { return; } (In other words, I want short if-statements on a single line but keep the {} around them) Currently I'm using the following configuration: AllowShortIfStatementsOnASingleLine: true AllowShortLoopsOnASingleLine: true AllowShortCaseLabelsOnASingleLine: true AllowShortFunctionsOnASingleLine: true...

Translating a character array into a integer string in C++


c++,arrays,string
I was trying to achieve translating a character array into a integer string and corresponding character to their alphabetical order. For instance: A(a) = 0 , Z(z) = 25. string key_char = argv[1]; string key_num; for (int i = 0; i < key_char.length(); i++){ if (isalpha(key_char[i])){ if (islower(key_char[i])){ key_num[i] =...

pointer to pointer dynamic array in C++


c++,arrays,pointers
I've been having bad luck with dynamic pointers when I want to close it. why the application wrote to memory after end of heap buffer? how can I close my array? int main() { . . int **W; W = new int* [n]; for (int i=1; i <= n; i++)...

No match for 'operator*' error


c++,c++11
Hello fellow programmers! I was going to write a small program for calculating total pay for different periods of time depending on the amount of hours and the salary that the user enters. I managed to make a small bit of the program but when I try to run it...

std::condition_variable – notify once but wait thread wakened twice


c++,multithreading
Here's a simple C++ thread pool implementation. It's an altered version orginated from https://github.com/progschj/ThreadPool. #ifndef __THREAD_POOL_H__ #define __THREAD_POOL_H__ #include <vector> #include <queue> #include <memory> #include <thread> #include <chrono> #include <mutex> #include <condition_variable> #include <future> #include <functional> #include <stdexcept> namespace ThreadPool { class FixedThreadPool { public: FixedThreadPool(size_t); template<class F, class......

Copy text and placeholders, variables to the clipboard


c++,qt,clipboard
In my application I want generate random numbers or strings with a text in front of it. It is important for me that the text won't appear in my window, but instead gets copied to the clipboard. int randomnumber = rand() % 46 + 1; QClipboard *cb = QApplication::clipboard(); cb->setText("Just...

create vector of objects on the stack ? (c++)


c++,vector,heap-memory
I am creating a temporary vector of pointers to myObject objects. But I am wondering about what happens to the objects I created... { std::vector<myObject *> myVector; myVector.reserve(5); for (int i = 0 ; i < 5 ; ++i){ myVector[i] = new myObject(); } } I assume that at the...

Confused about returns in stack template


c++,templates,generic-programming
I'm implementing a generic stack (with an array) in C++ and am confused about what to return in this situation: template <class T> T Stack<T>::pop(void) { if (size != 0) { return items[size - 1]; size--; } else { cerr << "Cannot pop from empty stack." << endl; return ???;...