0

I'm writing a code which has to save up as much space as possible.

for (int i = 0; i < Code.Length; i++){
    CodeInHex[i] = String.Format("{0:X}", Code[i]); // e.g. Dec value = -95, hex = "FFFFFFA1"
}

Is there a way to make heximal value equal to -A1 instead of "FFFFFFA1"? (saw it is allowed in c# here).

2
  • 1
    "As much as possible" is not the same as "as much as convenient". My guess is, that "as much as possible" will lead to something quite complex.
    – JoriO
    Oct 6, 2014 at 9:53
  • btw; lots and lots of encoding formats exist for these things; another option that leaps to mind would be "zigzag varint encoding, as hex" - that would be BD01 as hex Oct 6, 2014 at 10:05

1 Answer 1

2

Well, you could do it manually:

var val = Code[i];
CodeInHex[i] = val < 0 ? ("-" + (-val).ToString("X")) : val.ToString("X");

But! Negative hex is not a common way of representing negative numbers. It is only "allowed in C#" because it is the unary negation operator applied to a positive constant; i.e. when the question shows -0x1, it is "negate (some expression)", where "some expression" is 0x1.

9
  • 1
    If it is possible to make an own system representing numbers, then it would be wiser to use a much higher base on the numbers. For example, by using digits and upper and lower case alphabets could denote integers of base 62, which shortens the string representation significantly.
    – JoriO
    Oct 6, 2014 at 9:51
  • results in -5F instead of -A1
    – Saeb Amini
    Oct 6, 2014 at 9:51
  • Could you comment on second line a little?
    – user4074606
    Oct 6, 2014 at 9:52
  • @SaebAmini yes, that is correct; -A1 would be -161, not -95. The error here is the question, not the answer, IMO. Oct 6, 2014 at 9:54
  • 1
    @JoriO yes, that's fair; base-64 without padding might be a reasonable starting place. Oct 6, 2014 at 9:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.