online numero hexadecimal convertir codigo binario c# hex type-conversion

numero - C#convertir entero a hexadecimal y viceversa



hexadecimal a decimal online (10)

¿Cómo puedo convertir lo siguiente?

2934 (entero) a B76 (hex)

Déjame explicarte lo que estoy tratando de hacer. Tengo ID de usuario en mi base de datos que se almacenan como enteros. En lugar de que los usuarios hagan referencia a sus ID, quiero permitirles usar el valor hexadecimal. La razón principal es porque es más corto.

Así que no solo tengo que pasar de un entero a un hex, sino que también debo ir de un hex a otro.

¿Hay una manera fácil de hacer esto en C #?


Creé mi propia solución para convertir int en una cadena Hex y regresé antes de encontrar esta respuesta. No es sorprendente que sea considerablemente más rápido que la solución .net, ya que hay menos sobrecarga de código.

/// <summary> /// Convert an integer to a string of hexidecimal numbers. /// </summary> /// <param name="n">The int to convert to Hex representation</param> /// <param name="len">number of digits in the hex string. Pads with leading zeros.</param> /// <returns></returns> private static String IntToHexString(int n, int len) { char[] ch = new char[len--]; for (int i = len; i >= 0; i--) { ch[len - i] = ByteToHexChar((byte)((uint)(n >> 4 * i) & 15)); } return new String(ch); } /// <summary> /// Convert a byte to a hexidecimal char /// </summary> /// <param name="b"></param> /// <returns></returns> private static char ByteToHexChar(byte b) { if (b < 0 || b > 15) throw new Exception("IntToHexChar: input out of range for Hex value"); return b < 10 ? (char)(b + 48) : (char)(b + 55); } /// <summary> /// Convert a hexidecimal string to an base 10 integer /// </summary> /// <param name="str"></param> /// <returns></returns> private static int HexStringToInt(String str) { int value = 0; for (int i = 0; i < str.Length; i++) { value += HexCharToInt(str[i]) << ((str.Length - 1 - i) * 4); } return value; } /// <summary> /// Convert a hex char to it an integer. /// </summary> /// <param name="ch"></param> /// <returns></returns> private static int HexCharToInt(char ch) { if (ch < 48 || (ch > 57 && ch < 65) || ch > 70) throw new Exception("HexCharToInt: input out of range for Hex value"); return (ch < 58) ? ch - 48 : ch - 55; }

Código de tiempo:

static void Main(string[] args) { int num = 3500; long start = System.Diagnostics.Stopwatch.GetTimestamp(); for (int i = 0; i < 2000000; i++) if (num != HexStringToInt(IntToHexString(num, 3))) Console.WriteLine(num + " = " + HexStringToInt(IntToHexString(num, 3))); long end = System.Diagnostics.Stopwatch.GetTimestamp(); Console.WriteLine(((double)end - (double)start)/(double)System.Diagnostics.Stopwatch.Frequency); for (int i = 0; i < 2000000; i++) if (num != Convert.ToInt32(num.ToString("X3"), 16)) Console.WriteLine(i); end = System.Diagnostics.Stopwatch.GetTimestamp(); Console.WriteLine(((double)end - (double)start)/(double)System.Diagnostics.Stopwatch.Frequency); Console.ReadLine(); }

Resultados:

Digits : MyCode : .Net 1 : 0.21 : 0.45 2 : 0.31 : 0.56 4 : 0.51 : 0.78 6 : 0.70 : 1.02 8 : 0.90 : 1.25


Intenta lo siguiente para convertirlo en hexadecimal

public static string ToHex(this int value) { return String.Format("0x{0:X}", value); }

Y de regreso

public static int FromHex(string value) { // strip the leading 0x if ( value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { value = value.Substring(2); } return Int32.Parse(value, NumberStyles.HexNumber); }


Para Hex:

string hex = intValue.ToString("X");

A int:

int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber)


Una respuesta tardía a la moda, pero ¿ha considerado algún tipo de implementación de acortamiento de Integer ? Si el único objetivo es hacer que la identificación del usuario sea lo más corta posible, me interesaría saber si existe alguna otra razón aparente por la que específicamente requiera una conversión hexadecimal, a menos que, por supuesto, no la haya visto. ¿Es claro y conocido (si es necesario) que las ID de usuario son en realidad una representación hexadecimal del valor real?



int a hexadecimal

int a = 72;

Console.WriteLine ("{0: X}", a);

hexadecimal a int:

int b = 0xB76;

Console.WriteLine (b);


NET FRAMEWORK

Muy bien explicado y pocas líneas de programación BUEN TRABAJO.

// Store integer 182 int intValue = 182; // Convert integer 182 as a hex in a string variable string hexValue = intValue.ToString("X"); // Convert the hex string back to the number int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

PASCAL >> C #

http://files.hddguru.com/download/Software/Seagate/St_mem.pas

Algo de la vieja escuela muy antiguo procedimiento de pascal convertido a C #

/// <summary> /// Conver number from Decadic to Hexadecimal /// </summary> /// <param name="w"></param> /// <returns></returns> public string MakeHex(int w) { try { char[] b = {''0'',''1'',''2'',''3'',''4'',''5'',''6'',''7'',''8'',''9'',''A'',''B'',''C'',''D'',''E'',''F''}; char[] S = new char[7]; S[0] = b[(w >> 24) & 15]; S[1] = b[(w >> 20) & 15]; S[2] = b[(w >> 16) & 15]; S[3] = b[(w >> 12) & 15]; S[4] = b[(w >> 8) & 15]; S[5] = b[(w >> 4) & 15]; S[6] = b[w & 15]; string _MakeHex = new string(S, 0, S.Count()); return _MakeHex; } catch (Exception ex) { throw; } }



int valInt = 12; Console.WriteLine(valInt.ToString("X")); // C ~ possibly single-digit output Console.WriteLine(valInt.ToString("X2")); // 0C ~ always double-digit output


string HexFromID(int ID) { return ID.ToString("X"); } int IDFromHex(string HexID) { return int.Parse(HexID, System.Globalization.NumberStyles.HexNumber); }

Aunque realmente cuestiono el valor de esto. Tu objetivo declarado es hacer que el valor sea más corto, lo cual lo hará, pero eso no es un objetivo en sí mismo. Realmente quieres decir que sea más fácil de recordar o más fácil de escribir.

Si te refieres a más fácil de recordar, entonces estás dando un paso atrás. Sabemos que sigue siendo el mismo tamaño, simplemente codificado de manera diferente. Pero sus usuarios no sabrán que las letras están restringidas a ''A-F'', por lo que la ID ocupará el mismo espacio conceptual para ellos como si se permitiera la letra ''AZ''. Entonces, en lugar de ser como memorizar un número de teléfono, es más como memorizar un GUID (de longitud equivalente).

Si te refieres a escribir, en lugar de poder usar el teclado, el usuario ahora debe usar la parte principal del teclado. Es probable que sea más difícil de escribir, porque no será una palabra que sus dedos reconozcan.

Una opción mucho mejor es dejar que elijan un nombre de usuario real.