• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Pau

Member
More C++ questions. I'm trying to pixelate an image that has been read into an array by making nxn non-overlapping windows and making each value the average of the window. (The read and write image functions are given to us.)

So 2x2:

10 20 30 40
11 21 31 41
12 22 32 42
13 23 33 43

is transformed to:

16 16 36 36
16 16 36 36
18 18 37 37
18 18 37 37

However, my code only seems to be doing it for the first column of nxn windows in the image, and it's not even the whole column. What's making it stop? Why isn't it working for each nxn window in the whole row?

Code:
#include <iostream>
#include <cassert>
#include <cstdlib>
#include <fstream>
#include <cmath>

using namespace std;

const int MAXWIDTH = 512;
const int MAXHEIGHT = 512;

void readImage(int image[MAXWIDTH][MAXHEIGHT], int &width, int &height);
void writeImage(int image[MAXWIDTH][MAXHEIGHT], int width, int height);

int main() {
	//Ask user for number n
	int n;
	cout << "Enter n: " << endl;
	cin >> n;
			
	int imageArray[MAXWIDTH][MAXHEIGHT];
	int imageWidth, imageHeight;

	//Input PMM file into array
	readImage(imageArray, imageWidth, imageHeight);

	//Copy image to 2nd array
	int pixelatedImage[MAXWIDTH][MAXHEIGHT];

	for(int row = 0; row < imageHeight; row++)
	{
		for(int col = 0; col < imageWidth; col++)
		{		
			pixelatedImage[col][row] = imageArray[col][row];
		}
	}
	
	//make n x n windows
	int i = 0;
	int j = 0;
	int runningI = 0;
	int runningJ = 0;
	int runningTotal = 0;
	int average;
	int rowN = n;
	int colN = n;
	
	while(rowN < imageHeight)
	{
		while (colN < imageWidth)
		{
			//Get average of n x n window
			runningTotal = 0; 
			while(j < rowN)
			{
				while(i < colN)
				{
					runningTotal += pixelatedImage[j][i];
					i++;
				}
				j++;
				runningI = i;
				//Restart i
				i = i - n;
			}
			runningJ = j;
			//Restart j
			j = j - n;
			average = round(runningTotal/(n*n));
		
			//Write average to n x n window
			while(j < rowN)
			{
				while(i < colN)
				{
					pixelatedImage[j][i] = average;
					i++;
				}
				j++;
				//Restart i
				i = i - n;
			}
			//Restart j
			j = j - n;

			//Move to next n x n window column in current row of windows
			colN += n;
			i = runningI;
		}
		//Move down to next window row
		rowN += n;
		j = runningJ;
		
	}
	
	
	//Write the 2nd array into outImage
	writeImage(pixelatedImage, imageWidth, imageHeight);

}

// reads a PPM file.
// Notice that: width and height are passed by reference!
void readImage(int image[MAXWIDTH][MAXHEIGHT], int &width, int &height) {
  char c;
  int x;
  ifstream instr;
  instr.open("inImage.pgm");
  
  // read the header P3
  instr >> c;  assert(c == 'P');
  instr >> c;  assert(c == '2');

  // skip the comments (if any)
  while ((instr>>ws).peek() == '#') { instr.ignore(4096, '\n'); }

  instr >> width; 
  instr >> height;

  assert(width <= MAXWIDTH);
  assert(height <= MAXHEIGHT);
  int max;
  instr >> max;
  assert(max == 255);

  for (int row = 0; row < height; row++) 
    for (int col = 0; col < width; col++) 
      instr >> image[col][row];
  instr.close();
  return;
}

void writeImage(int image[MAXWIDTH][MAXHEIGHT], int width, int height) {
  ofstream ostr;
  ostr.open("outImage.pgm");
  if (ostr.fail()) {
    cout << "Unable to write file\n";
    exit(1);
  };
  
  // print the header
  ostr << "P2" << endl;
  // width, height
  ostr << width << ' '; 
  ostr << height << endl;
  ostr << 255 << endl;

  for (int row = 0; row < height; row++) {
    for (int col = 0; col < width; col++) {
      assert(image[col][row] < 256);
      assert(image[col][row] >= 0);
      ostr << image[col][row] << ' ';
      // lines should be no longer than 70 characters
      if ((col+1)%16 == 0) ostr << endl;
    }
    ostr << endl;
  }
  ostr.close();
  return;
}
 
More C++ questions. I'm trying to pixelate an image that has been read into an array by making nxn non-overlapping windows and making each value the average of the window. (The read and write image functions are given to us.)

This is more code than I want to play find-the-bug in honestly, but for starters I would try making the following function:

int compute_average(int top_left, int top_right, int size)

Then you can write some code in your main function to pass in your test array with some values and see if the value you get back is what you expect.

After that, I would suggest running it under a debugger. You can probably find the problem in about 30 seconds stepping through under a debugger.
 

Water

Member
C++ arrays are extremely barebones and essentially are meant to just represent a type-safe chunk of memory. They can't have any features that would require having extra storage per array, transparently moving stuff around in memory (which would invalidate your pointers), or extra checks on every array access. That's why they're so tricky to use. If you want a data structure with the performance characteristics of an array but don't need it to be low level, it's nearly always better to use a vector. But even vectors don't check index bounds unless you use the at method.

I want to put that in stronger terms. std::vector and std::array are the standard array datatypes in C++. Good intro to C++ courses, books and materials teach them first, while legacy C arrays should be covered later if at all. It's not good style to use a C array unless you have a specific reason to do so.

Although standard vector indexing doesn't do bounds checking, you can use debug builds and get bounds checking, which for a lot of purposes (eg. programming classes, many types of projects) is roughly as useful as if bounds checking was always on.
 
Come join us in Web Development thread if you want to because this thread moves quite fast so it's easy miss these ones.

That import is an ES6/ES2015 type of import declaration so like you said, you either need to transpile it (using Babel for example) or need to have browser that supports those.

Difference between NPM and Bower is that Bower is meant for frontend packages, but due how JavaScript apps are now built it's quickly becoming a bit obsolete: you can install your packages with NPM and then bundle them for browser with Browserify, Webpack or Rollup. Why does there need to be 3 of different ones? They have many similarities, but also differ in their complexity. Just pick one and use that, it won't be hard to switch around later.

Then comes the part where people come in and say that "oh JS was soooo much better when you didn't need all these tools blah blah" but ignore that noise and do the one time setup (if you are already transpiling JSX files you have most of these done already).

1. Install Node JS (which installs npm)
2. Create your application folder
3. Open your console
4. Install react and react-router (npm install react react-dom react-router)
5. Create foo.jsx
6. insert the import statement (or just follow this: https://github.com/rackt/react-router)
7. Transpile the file with the tool of your choice. https://babeljs.io/docs/setup/#babel_cli
Check this document for pretty much every example. I myself use Grunt + Browserify (with Babelify), but something else might fit you better. And like I said, when you understand the concept, it's easy to switch around when needed.

Ah, I forgot that thread existed. Also, thanks for the instructions. I'll try that later.
 

NotBacon

Member
I cut a bunch of stuff out. The array itself will hold anywhere from 1-25 of those objects(?) in it. Here's the actual json, removed a few lines at the end and changed some values that are meant to be internal use only.
Code:
{  
   "Start":0,
   "Count":25,
   "ResultCount":25,
"Results":[  
      {  
         "Links":{  },
         "Id":{  },
         "HopperId":"hexcode",
         "MapId":"hexcode",
         "MapVariant":{  },
         "GameBaseVariantId":"hex",
         "GameVariant":{  },
         "MatchDuration":"PT8M46.2464205S",
         "MatchCompletedDate":{  },
         "Teams":[  ],
         "Players":[  
            {  }
         ],
         "IsTeamGame":true,
         "SeasonId":"hex"
      },
      {  
         "Links":{  
            "StatsMatchDetails":{  
               "AuthorityId":"spartanstats",
               "Path":"urlpath",
               "QueryString":null,
               "RetryPolicyId":"exponentialretry",
               "TopicName":"",
               "AcknowledgementTypeId":0,
               "AuthenticationLifetimeExtensionSupported":false
            },
            "UgcFilmManifest":{  
               "AuthorityId":"ugc",
               "Path":"urlpath",
               "QueryString":"?view=film-manifest",
               "RetryPolicyId":"exponentialretry",
               "TopicName":"",
               "AcknowledgementTypeId":0,
               "AuthenticationLifetimeExtensionSupported":false
            }
         },
         "Id":{  
            "MatchId":"hex",
            "GameMode":1
         },
         "HopperId":"hex",
         "MapId":"hex",
         "MapVariant":{  
            "ResourceType":3,
            "ResourceId":"hex",
            "OwnerType":3,
            "Owner":""
         },
         "GameBaseVariantId":"hex",
         "GameVariant":{  
            "ResourceType":2,
            "ResourceId":"hex",
            "OwnerType":3,
            "Owner":""
         },
         "MatchDuration":"PT8M20.5707417S",
         "MatchCompletedDate":{  
            "ISO8601Date":"2015-11-08T00:00:00Z"
         },
         "Teams":[  
            {  
               "Id":1,
               "Score":50,
               "Rank":1
            },
            {  
               "Id":0,
               "Score":40,
               "Rank":2
            }
         ],
         "Players":[  
            {  
               "Player":{  
                  "Gamertag":"Karl2177",
                  "Xuid":null
               },
               "TeamId":0,
               "Rank":6,
               "Result":1,
               "TotalKills":10,
               "TotalDeaths":13,
               "TotalAssists":1,
               "PreMatchRatings":null,
               "PostMatchRatings":null
            }
         ],
         "IsTeamGame":true,
         "SeasonId":"hex"
      }, ...
    ]
}

Okay now show us the Java class you're using for deserialization.
 

Karl2177

Member
Okay now show us the Java class you're using for deserialization.

Variables are capitalized because I was lazy and didn't want to write the Gson variable

Code:
package halo5test;

import java.util.List;

public class MatchContainer {
	private int Start;
	private int Count;
	private int ResultCount;
	private List<Results> Results;
	
	public class Results{
		private List<Link> Links;
		private Id Id;
		private String HopperId;
		private String MapId;
		private MapVariant MapVariant;
		private String GameBaseVariantId;
		private GameVariant GameVariant;
		private String MatchDuration;
		private MatchCompletedDate MatchCompletedDate;
		private List<Team> Teams;
		private List<Players> Players;
		private boolean IsTeamGame;
		private String SeasonId;

		public ResultContainer(){
			
		}
                //To reduce code size on gaf, the other classes are here also.
}
 

JeTmAn81

Member
This is more code than I want to play find-the-bug in honestly, but for starters I would try making the following function:

int compute_average(int top_left, int top_right, int size)

Then you can write some code in your main function to pass in your test array with some values and see if the value you get back is what you expect.

After that, I would suggest running it under a debugger. You can probably find the problem in about 30 seconds stepping through under a debugger.

I have no idea why I ended up tracing Pau's code but it seems to me that there's maybe not any handling for cases when the size of the nxn area will go beyond the bounds of the original image?

So if you're doing 2x2 but the image is actually 5x5, what happens in the case when the pixelization area only has one horizontal pixel to work with (it already did 0-1, then 2-3, but only horizontal position 4 is left in the 5-width image size)?
 

Pau

Member
This is more code than I want to play find-the-bug in honestly, but for starters I would try making the following function:

int compute_average(int top_left, int top_right, int size)

Then you can write some code in your main function to pass in your test array with some values and see if the value you get back is what you expect.

After that, I would suggest running it under a debugger. You can probably find the problem in about 30 seconds stepping through under a debugger.
The values are what I expect, but something was stopping the loop. I just rewrote it using a for loop instead and without runningI and runningJ. It works now. :eek:

I have no idea why I ended up tracing Pau's code but it seems to me that there's maybe not any handling for cases when the size of the nxn area will go beyond the bounds of the original image?

So if you're doing 2x2 but the image is actually 5x5, what happens in the case when the pixelization area only has one horizontal pixel to work with (it already did 0-1, then 2-3, but only horizontal position 4 is left in the 5-width image size)?
It wasn't handling any case, even if the nxn areas didn't go beyond the bounds of the original image. Now that I fixed it, it seems like the last row and column of windows are just cut off.
 

JeTmAn81

Member
It wasn't handling any case, even if the nxn areas didn't go beyond the bounds of the original image. Now that I fixed it, it seems like the last row and column of windows are just cut off.

Probably for the best, as I looked at the code I kept thinking there must been an easier way of traversing the array.
 

NotBacon

Member
Variables are capitalized because I was lazy and didn't want to write the Gson variable

Code:
package halo5test;

import java.util.List;

public class MatchContainer {
	private int Start;
	private int Count;
	private int ResultCount;
	private List<Results> Results;
	
	public class Results{
		private List<Link> Links;
		private Id Id;
		private String HopperId;
		private String MapId;
		private MapVariant MapVariant;
		private String GameBaseVariantId;
		private GameVariant GameVariant;
		private String MatchDuration;
		private MatchCompletedDate MatchCompletedDate;
		private List<Team> Teams;
		private List<Players> Players;
		private boolean IsTeamGame;
		private String SeasonId;

		public ResultContainer(){
			
		}
                //To reduce code size on gaf, the other classes are here also.
}

In this snippet I see:
Code:
...
public class Results{
	private List<Link> Links;
        ...

so you're telling Gson that you expect an array of Link objects
Code:
"Links":[  ],
within each Results object.

But really it's just a single JSON object:
Code:
...
"Results":[  
{  
    [B]"Links":{  }[/B],
    "Id":{  },
    ...
 

Karl2177

Member
In this snippet I see:


so you're telling Gson that you expect an array of Link objects

within each Results object.

But really it's just a single JSON object:

Oh shoot. Thanks. :)

EDIT: Quick question: There are two different structures to the Links object in the JSON file. The first one I showed before(but I'll show it again) and the second one is here. The first one is inside the Results, but the second one is outside in the MatchContainer. I can just create the Links class and have a StatsMatchDetails object, a UgcFilmManifest object, and a Self object; but only instantiate the first 2 in the Results and the Self one in the final. That wouldn't fuck things up would they?

Code:
"Links":{  
            "StatsMatchDetails":{  
               "AuthorityId":"spartanstats",
               "Path":"h5/arena/matches/77c656fc-3443-4636-ad81-389bcb764e4b",
               "QueryString":null,
               "RetryPolicyId":"exponentialretry",
               "TopicName":"",
               "AcknowledgementTypeId":0,
               "AuthenticationLifetimeExtensionSupported":false
            },
            "UgcFilmManifest":{  
               "AuthorityId":"ugc",
               "Path":"/h5/films/77c656fc-3443-4636-ad81-389bcb764e4b",
               "QueryString":"?view=film-manifest",
               "RetryPolicyId":"exponentialretry",
               "TopicName":"",
               "AcknowledgementTypeId":0,
               "AuthenticationLifetimeExtensionSupported":false
            }
         }

Code:
"Links":{  
      "Self":{  
         "AuthorityId":"spartanstats",
         "Path":"/h5/players/Karl2177/matches",
         "QueryString":"?include-xuids=false&view=full&include-ratings=false",
         "RetryPolicyId":"",
         "TopicName":"",
         "AcknowledgementTypeId":0,
         "AuthenticationLifetimeExtensionSupported":false
      }
   }
 

NotBacon

Member
Oh shoot. Thanks. :)

EDIT: Quick question: There are two different structures to the Links object in the JSON file. The first one I showed before(but I'll show it again) and the second one is here. The first one is inside the Results, but the second one is outside in the MatchContainer. I can just create the Links class and have a StatsMatchDetails object, a UgcFilmManifest object, and a Self object; but only instantiate the first 2 in the Results and the Self one in the final. That wouldn't fuck things up would they?

Code:
"Links":{  
            "StatsMatchDetails":{  
               "AuthorityId":"spartanstats",
               "Path":"h5/arena/matches/77c656fc-3443-4636-ad81-389bcb764e4b",
               "QueryString":null,
               "RetryPolicyId":"exponentialretry",
               "TopicName":"",
               "AcknowledgementTypeId":0,
               "AuthenticationLifetimeExtensionSupported":false
            },
            "UgcFilmManifest":{  
               "AuthorityId":"ugc",
               "Path":"/h5/films/77c656fc-3443-4636-ad81-389bcb764e4b",
               "QueryString":"?view=film-manifest",
               "RetryPolicyId":"exponentialretry",
               "TopicName":"",
               "AcknowledgementTypeId":0,
               "AuthenticationLifetimeExtensionSupported":false
            }
         }

Code:
"Links":{  
      "Self":{  
         "AuthorityId":"spartanstats",
         "Path":"/h5/players/Karl2177/matches",
         "QueryString":"?include-xuids=false&view=full&include-ratings=false",
         "RetryPolicyId":"",
         "TopicName":"",
         "AcknowledgementTypeId":0,
         "AuthenticationLifetimeExtensionSupported":false
      }
   }

That should work, I think. I'm pretty sure Gson just ignores member variables when it can't find a matching JSON value. So if you create a Links class with all 3 objects, you should be able to re-use it.

And you don't have to instantiate anything as Gson does that for you.
 

Karl2177

Member
That should work, I think. I'm pretty sure Gson just ignores member variables when it can't find a matching JSON value. So if you create a Links class with all 3 objects, you should be able to re-use it.

And you don't have to instantiate anything as Gson does that for you.

Yep. It did. Thanks for your help through this. :)
 
What's the best way to practice setting up a server in Java? Any tutorials around?

You'll need to be a bit more specific. I'm gonna assume you mean a web server, but even there you have about a million different options. It used to be all about Java EE (JSF/JSP, Hibernate, Tomcat) but lately there's been a lot of development for smaller, more modern frameworks inspired by Rails (Play Framework), Flask/Sinatra (Dropwizard, Spark, Spring Boot) and Node.js (Vert.x, I think).
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
Alright, this might be a stupid question but I'm trying to wrap my head around it:

Javascript, though I'm trying to half-ass learn C as well
Code:
var thisShouldBeTrueAtStart = true;
do {
    console.log("This should loop once because true!");
    thisShouldBeTrueAtStart = false;
}
while(thisShouldBeTrueAtStart);

while(thisShouldBeTrueAtStart); {
     return "This should loop once!";
     thisShouldBeTrueAtStart = false;
}

Okay, that works. But if I try to make "thisShouldBeTrueAtStart" a number like 10 and then try to count down, I get an infinite loop. Why? Because the variable is trying to increment each loop?
 

Haly

One day I realized that sadness is just another word for not enough coffee.
Can I see the infinite loop code? And which loop is looping infinitely?

Also you have a semicolon after your second while statement.
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
Can I see the infinite loop code? And which loop is looping infinitely?

Also you have a semicolon after your second while statement.

Yeah, typo on my part.

Essentially I'm running through the Javascript tutorial at Codecademy to refresher myself.

This is the finished code:

Code:
understand = true;

while(understand){
	console.log("I'm learning while loops!");
	understand = false;
	
}

However, if you set it as:

Code:
understand = true;

while(understand = true){
	console.log("I'm learning while loops!");
	understand = false;
	
}

It loops. I guess due to trying to reset the understand variable to true which it already is?
 

JeTmAn81

Member
Yeah, typo on my part.

Essentially I'm running through the Javascript tutorial at Codecademy to refresher myself.

This is the finished code:

Code:
understand = true;

while(understand){
	console.log("I'm learning while loops!");
	understand = false;
	
}

However, if you set it as:

Code:
understand = true;

while(understand = true){
	console.log("I'm learning while loops!");
	understand = false;
	
}

It loops. I guess due to trying to reset the understand variable to true which it already is?

You're setting understand to true in that second loop. To compare, you should write understand == true instead of understand = true.

Also, if you want to use a number as a loop condition, I think you'll probably need to run it through parseInt to make sure Javascript knows it's a number (no type system, remember?).
 

Koren

Member
You're setting understand to true in that second loop. To compare, you should write understand == true instead of understand = true.
I'd say it would be better to write true == understand instead of understand == true.

That's exactly the same test, it won't change anything here.

But in most languages that uses == to perform a test of equality, "true" (or any immediate value) isn't a correct lvalue. By getting used to the idea of placing the immediate value to the left of ==, you'll get compiler errors each time you write = instead of == by mistake, instead of a silent bug (or, if you're really lucky, a compiler warning).

It may be slightly less natural, especially at first, but it's really a nice trick.
 

Fishlake

Member
I'd say it would be better to write true == understand instead of understand == true.

That's exactly the same test, it won't change anything here.

But in most languages that uses == to perform a test of equality, "true" (or any immediate value) isn't a correct lvalue. By getting used to the idea of placing the immediate value to the left of ==, you'll get compiler errors each time you write = instead of == by mistake, instead of a silent bug (or, if you're really lucky, a compiler warning).

It may be slightly less natural, especially at first, but it's really a nice trick.

Wow that is really smart and simple. I'll have to do that from now on.
 
I'd say it would be better to write true == understand instead of understand == true.

That's exactly the same test, it won't change anything here.

But in most languages that uses == to perform a test of equality, "true" (or any immediate value) isn't a correct lvalue. By getting used to the idea of placing the immediate value to the left of ==, you'll get compiler errors each time you write = instead of == by mistake, instead of a silent bug (or, if you're really lucky, a compiler warning).

It may be slightly less natural, especially at first, but it's really a nice trick.

The reverse conditionals always make my brain melt. Good thing that some languages have code quality tools so you don't have to degrade to such brutality :p
 

Koren

Member
Wow that is really smart and simple. I'll have to do that from now on.
The idea isn't mine (I can't remember where I've seen it first), but I found it really clever and it saved me a couple of times already.

The reverse conditionals always make my brain melt.
Honestly, I've used them for years, and I still don't like them. But I like even more spending hours looking for such a stupid bug, so...

I agree that having a language that avoid the issue is better (although many do it by avoiding completely assignments in tests, which is sometimes unfortunate).
 
Wow that is really smart and simple. I'll have to do that from now on.

It's a pet peeve of mine (and I think a lot of people share it) when people compare against true or false in conditionals.

Code:
while (true == understand) => while (understand)

while (false == understand) => while (!understand)

Also if you use a naming convention to identify your boolean variables, it reads more clearly.

Code:
while (isUnderstood) { ... }
while (!isUnderstood) { ... }
 
It's a pet peeve of mine (and I think a lot of people share it) when people compare against true or false in conditionals.

Code:
while (true == understand) => while (understand)

while (false == understand) => while (!understand)

Also if you use a naming convention to identify your boolean variables, it reads more clearly.

Code:
while (isUnderstood) { ... }
while (!isUnderstood) { ... }

How about

Code:
if (true == understand) {
  return true;
} else {
  return false,
}
Where's your god now
 

Koren

Member
It's a pet peeve of mine (and I think a lot of people share it) when people compare against true or false in conditionals.
Depends on the language, I'd say... When a language refuse to compare e.g. an int and a boolean, and has dynamic typing, explicit comparison can be useful.

In most cases (including this example), though, I agree (and especially with better naming).

Seeing students writing this is still two steps less infuriating than seeing them using the drop menus with the mouse to run code instead of using the keyboard shortcut (argh!) ^_^

The reverse conditional trick is mostly useful for non-boolean immediate values, in fact.
 

Koren

Member
How about

Code:
if (true == understand) {
  return true;
} else {
  return false,
}
Where's your god now

Code:
if (understand != true) {
    return false;
}

if (understand != false) {
    return true;
}
I've seen it.

For real.


Granted, you can see anything in students code...

One of my best memories is this one: a group of 5 had to design (with a lot of help) a compiler for a given language. They call me for help, because they have a bug they can't find after a whole day looking for it.

They explain me that they have an int that contains a decimal integer. The want to convert it in an hexadecimal integer.

It took me a whole minute to understand what they wanted to do (read: a function that takes x and returns x, or in other terms something totally useless because they didn't understand at all the principles of binary storage of values).

They designed a function that would:
- allocate a buffer
- convert the int into a string in the buffer where the number is in its decimal form
- work on the string to convert it to hexadecimal form, just with character manipulation
- convert the string into an int

5 people and a whole day to write a function that do nothing... with a bug inside.

Their faces when I managed to explain them why they were completely wrong were priceless. I know you do a lot of bad things when you learn, I've done plently of them myself. but still, for students in their third year in one of the best computer science school of the country, that was quite unexpected for the fresh teacher I was.
 
Their faces when I managed to explain them why they were completely wrong were priceless. I know you do a lot of bad things when you learn, I've done plently of them myself. but still, for students in their third year in one of the best computer science school of the country, that was quite unexpected for the fresh teacher I was.

I was a tutor for a while and remember a student who had made it through a couple programming classes and didn't know how to compile a program.

It was more depressing than anything. I feel bad that so many people were wasting their time at school.
 
Granted, you can see anything in students code...

One of my best memories is this one: a group of 5 had to design (with a lot of help) a compiler for a given language. They call me for help, because they have a bug they can't find after a whole day looking for it.

They explain me that they have an int that contains a decimal integer. The want to convert it in an hexadecimal integer.

It took me a whole minute to understand what they wanted to do (read: a function that takes x and returns x, or in other terms something totally useless because they didn't understand at all the principles of binary storage of values).

They designed a function that would:
- allocate a buffer
- convert the int into a string in the buffer where the number is in its decimal form
- work on the string to convert it to hexadecimal form, just with character manipulation
- convert the string into an int


5 people and a whole day to write a function that do nothing... with a bug inside.

Their faces when I managed to explain them why they were completely wrong were priceless. I know you do a lot of bad things when you learn, I've done plently of them myself. but still, for students in their third year in one of the best computer science school of the country, that was quite unexpected for the fresh teacher I was.
Ok, I'm literally the last person joining the party when it comes to programming but...
what.
 

Koren

Member
Ok, I'm literally the last person joining the party when it comes to programming but...
what.
That was my reaction...

I still don't understand how they went through a 20+ hours assembly course, a 20+ hours compilation course, and probably 500+ hours of computer science and still don't have a clue of what a memory cell contains.

All *5* of them.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
I never learned compilers and assembly, so what is the idiomatic way of doing dec > hex?
 

Koren

Member
I never learned compilers and assembly, so what is the idiomatic way of doing dec > hex?
In memory, values are stored in binary form.

The basic idea of converting is nonsense.

If you have a string with a number in its decimal form, the conversion is done between decimal and binary during the string > int conversion.

If you want the result as an hex string, it's done during the int > string conversion.

But the int itself isn't decimal or hex...

(assuming you don't consider bcd but that's a wholly different issue)
 
It's like asking how to convert text from Arial to Times New Roman. If you're trying to figure out how to add and remove individual pixels from the screen to change from one specific font to another something's wrong.
 

leroidys

Member
I interviewed someone recently for a senior position that did something similar. Took a string representation of hexadecimal, converted it to a 'hexadecimal int', then looped over it bit by bit to build... A 'decimal int'.
 

upandaway

Member
In memory, values are stored in binary form.

The basic idea of converting is nonsense.

If you have a string with a number in its decimal form, the conversion is done between decimal and binary during the string > int conversion.

If you want the result as an hex string, it's done during the int > string conversion.

But the int itself isn't decimal or hex...

(assuming you don't consider bcd but that's a wholly different issue)
I have computer systems class this semester and this was one of the things the professor repeated until everyone got it in the first/second lectures. Then he put this question in our homework:

Write a function in C that takes 2 numbers (say 0xAAAAAAAA and 0xBBBBBBBB) and returns 0xAABBBBBB, and some people just had no clue how to do it because it's in hex. The crazy thing is the homework included a main.c file that tests our function, and it had a printf with %x right there.
 
I have computer systems class this semester and this was one of the things the professor repeated until everyone got it in the first/second lectures. Then he put this question in our homework:

Write a function in C that takes 2 numbers (say 0xAAAAAAAA and 0xBBBBBBBB) and returns 0xAABBBBBB, and some people just had no clue how to do it because it's in hex. The crazy thing is the homework included a main.c file that tests our function, and it had a printf with %x right there.

I guess I'm clueless too because I'm not sure how you'd do that using printf.

Mine would be

Code:
unsigned int combine(unsigned int a, unsigned int b) {
    return a & 0xff000000 | b & 0x00ffffff;
}
 

upandaway

Member
I guess I'm clueless too because I'm not sure how you'd do that using printf.

Mine would be

Code:
unsigned int combine(unsigned int a, unsigned int b) {
    return a & 0xff000000 | b & 0x00ffffff;
}
Sorry I didn't mean do it using the printf, I meant the we got a main.c file with this line:
printf("%x", merge(0xAAAAAAAA, 0xBBBBBBBB));
which should have been somewhat of a clue to what hex really is in C

Regarding your answer we couldn't assume that an int is exactly 4 bytes, so it was slightly different, but yeah
 

Haly

One day I realized that sadness is just another word for not enough coffee.
I saw this somewhere, might've been in this thread, or a book or some article.

Code:
return boolVar ? true : false
 
We have apparently reached the terrible Boolean expression portion of the thread again, so I guess it is also again time for a friendly reminder, courtesy of an age old quote.

"Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live."
 
They designed a function that would:
- allocate a buffer
- convert the int into a string in the buffer where the number is in its decimal form
- work on the string to convert it to hexadecimal form, just with character manipulation
- convert the string into an int

I'm not sure I understand what this all means.

So the function would take an int like 23, convert it to the string "23", convert that string "23" into the string "17" (23 is 17 in hexadecimal), and then convert that "17" into the int 17?

And this was bad/wrong because numbers are stored in binary so there was no real need to do all those conversions?
 
Top Bottom